From ede70cfac5d91f702a1ada5d23833bc9cf09fb35 Mon Sep 17 00:00:00 2001 From: bc-travis-ci Date: Mon, 13 Jan 2025 08:30:51 +0000 Subject: [PATCH] chore(release): 1.696.0 [skip ci] --- CHANGELOG.md | 7 +++++++ dist/checkout-button.js | 2 +- dist/checkout-button.umd.js | 2 +- dist/checkout-sdk.js | 2 +- dist/checkout-sdk.js.map | 2 +- dist/checkout-sdk.umd.js | 2 +- dist/checkout-sdk.umd.js.map | 2 +- dist/hosted-form-v2-iframe-host.js | 2 +- dist/hosted-form-v2-iframe-host.umd.js | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 11 files changed, 18 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 605e99d0cb..d07a27d815 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +## [1.696.0](https://github.com/bigcommerce/checkout-sdk-js/compare/v1.695.2...v1.696.0) (2025-01-13) + + +### Features + +* **payment:** PAYPAL-4995 added check for teardown call in deinitialize method ([1e16475](https://github.com/bigcommerce/checkout-sdk-js/commit/1e16475970a13dbfb40045fdf6a3bc85cdd12425)) + ### [1.695.2](https://github.com/bigcommerce/checkout-sdk-js/compare/v1.695.1...v1.695.2) (2025-01-06) diff --git a/dist/checkout-button.js b/dist/checkout-button.js index f583da4303..3a3d7b2cbc 100644 --- a/dist/checkout-button.js +++ b/dist/checkout-button.js @@ -1,2 +1,2 @@ -(()=>{"use strict";var t={n:e=>{var n=e&&e.__esModule?()=>e.default:()=>e;return t.d(n,{a:n}),n},d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{createCheckoutButtonInitializer:()=>Ff,createTimeout:()=>r.createTimeout});var n={};t.r(n),t.d(n,{createAmazonPayV2ButtonStrategy:()=>Rs,createApplePayButtonStrategy:()=>rd,createBoltButtonStrategy:()=>gd,createBraintreeVenmoButtonStrategy:()=>Dd,createBraintreeVisaCheckoutButtonStrategy:()=>Cd,createGooglePayAdyenV2ButtonStrategy:()=>Dl,createGooglePayAdyenV3ButtonStrategy:()=>Ml,createGooglePayAuthorizeDotNetButtonStrategy:()=>xl,createGooglePayBraintreeButtonStrategy:()=>bl,createGooglePayCheckoutComButtonStrategy:()=>Hl,createGooglePayCybersourceButtonStrategy:()=>Zl,createGooglePayOrbitalButtonStrategy:()=>$l,createGooglePayPayPalCommerceButtonStrategy:()=>Rl,createGooglePayStripeButtonStrategy:()=>pp,createGooglePayTdOnlineMartButtonStrategy:()=>Sp,createGooglePayWorldpayAccessButtonStrategy:()=>mp,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>If,createPayPalCommerceButtonStrategy:()=>$p,createPayPalCommerceCreditButtonStrategy:()=>pf,createPayPalCommerceVenmoButtonStrategy:()=>vf,createPaypalExpressButtonStrategy:()=>Uf});const r=require("@bigcommerce/request-sender"),o=require("@bigcommerce/form-poster"),i=require("@bigcommerce/data-store");var a,c=(a=function(t,e){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},a(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const u=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return c(e,t),e}(Error);var s=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),d={body:{},headers:{},status:0},l=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,c=e||d,u=c.body,s=c.headers,l=c.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=s,a.status=l,a.errors=i||[],a}return s(e,t),e}(u);const p=l;var f=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const h=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return f(e,t),e}(p);var y=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return y(e,t),e}(Error);var g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),v={body:{},headers:{},status:0},b=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,c=e||v,u=c.body,s=c.headers,d=c.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=s,a.status=d,a.errors=i||[],a}return g(e,t),e}(m);const _=b;var w=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const S=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return w(e,t),e}(_),C=require("lodash");var I=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0}})),W=$n(F,(function(t){return function(e){return!(!e||!e.nonce)||t()===ur||t()===sr}})),(0,Wn.memoizeOne)((function(t,e){return{getPaymentId:x({checkout:t,order:e}),getPaymentIdOrThrow:U({checkout:t,order:e}),getPaymentStatus:F({checkout:t,order:e}),getPaymentStatusOrThrow:B({checkout:t,order:e}),getPaymentToken:q({checkout:t,order:e}),getPaymentTokenOrThrow:j({checkout:t,order:e}),getPaymentRedirectUrl:G({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:V({checkout:t,order:e}),isPaymentDataRequired:H({checkout:t,order:e}),isPaymentDataSubmitted:W({checkout:t,order:e})}}))),Et=function(){var t=$n((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=$n((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,Wn.memoizeOne)((function(n){return void 0===n&&(n=pr),{getApplyError:t(n),isApplying:e(n)}}))}(),Ot=function(){var t=$n((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=$n((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,Wn.memoizeOne)((function(n){return void 0===n&&(n=Un),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Pt=(K=$n((function(t){return t.data}),(function(t){return function(){return t}})),Z=$n((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),Q=$n((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,Wn.memoizeOne)((function(t){return void 0===t&&(t=An),{getEmail:K(t),getSendError:Z(t),isSending:Q(t)}}))),At=function(){var t=$n((function(t){return t.data}),(function(t){return function(){return t}})),e=$n((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=$n((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=$n((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,Wn.memoizeOne)((function(o){return void 0===o&&(o=Zt),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n,r=J(t.billingAddress),o=X(t.cart),i=$(t.checkoutButton),a=et(t.countries),c=nt(t.coupons),u=rt(t.customer),s=it(t.customerStrategies),d=At(t.extensions),l=ut(t.formFields),p=at(t.giftCertificates),f=ct(t.instruments),h=St(t.orderBillingAddress),y=st(t.paymentMethods),m=ft(t.paymentProviderCustomer),g=lt(t.paymentStrategies),v=pt(t.pickupOptions),b=ht(t.remoteCheckout),_=yt(t.consignments),w=mt(t.shippingCountries),S=gt(t.shippingStrategies),C=Ot(t.subscriptions),I=Et(t.storeCredit),E=Pt(t.signInEmail),O=vt(t.consignments,o),P=_t(t.checkout,r,o,O,c,u,p),A=wt(t.order,h,c),T=Ct(P,A),k={billingAddress:r,cart:o,checkout:P,checkoutButton:i,config:tt(t.config,t.formFields),consignments:O,countries:a,coupons:c,customer:u,customerStrategies:s,extensions:d,form:l,giftCertificates:p,instruments:f,order:A,orderBillingAddress:h,payment:T,paymentMethods:y,paymentProviderCustomer:m,paymentStrategies:g,pickupOptions:v,remoteCheckout:b,shippingAddress:_,shippingCountries:w,shippingStrategies:S,signInEmail:E,subscriptions:C,storeCredit:I};return e.shouldWarnMutation?(n=k,Object.keys(n).reduce((function(t,e){return t[e]=rr(n[e]),t}),{})):k}}var yr=function(){return yr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadPaymentMethod",null),t}();const Cr=Sr;var Ir;!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(Ir||(Ir={}));const Er=Ir;var Or="This API endpoint is for internal use only and may change in the future",Pr={"X-Checkout-SDK-Version":"1.695.2"},Ar=function(){return Ar=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new to(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,c="/api/storefront/checkout/".concat(t),u=eo({Accept:Er.JsonV1},Pr);return this._requestSender.put(c,{params:{include:Jr(Xr,i)},body:e,headers:u,timeout:a})},t}();const ro=no,oo=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,C.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return"".concat(t.id).localeCompare("".concat(e.id))})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}();var io=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const ao=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return io(e,t),e}(m),co=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new Qn(Kn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new oo;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new ao(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,C.isEqual)((0,C.map)(t,"code"),(0,C.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,C.isEqual)((0,C.map)(t,"code"),(0,C.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,o=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:o}},t}();const uo=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return M.Observable.create((function(n){n.next((0,i.createAction)(st.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,i.createAction)(st.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,i.createErrorAction)(st.LoadConfigFailed,t))}))}))},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadConfig",null),t}();var so=function(){return so=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new to(t);throw t}))},t}();const po=lo;function fo(t){var e=t;return"object"==typeof e&&"object"==typeof e.payload&&"string"==typeof e.payload.token}var ho=function(){return ho=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadFormFields",null),t}();const _o=bo;var wo=function(){return wo=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&Mo(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Uo],t.prototype,"_handleMessage",null),t}();const qo=Bo;var jo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Go=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return jo(e,t),e}(m);var Vo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Ho=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return Vo(e,t),e}(m);var Yo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Wo=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return Yo(e,t),e}(m);var Ko=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function c(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,c)}u((r=r.apply(t,e||[])).next())}))},Zo=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!c?a:"".concat(a," ").concat("/"," ").concat(c)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const ra=na,oa=require("card-validator"),ia=function(){function t(){}return t.prototype.format=function(t){var e=(0,oa.number)(t).card;if(!e)return t;var n=(0,C.max)((0,oa.creditCardType)(t).map((function(t){return(0,C.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,oa.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();var aa=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new Qn(Kn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,C.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"==typeof t&&"address"in t},t}();const Oa=Ea;var Pa=function(){return Pa=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([_c],t)}();const Sc=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([_c],t)}();function Cc(t){return{errors:new wc(t),statuses:new Sc(t)}}var Ic=function(){return Ic=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([Uo],t)}();const Oc=Ec;var Pc=function(){return Pc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t}function pu(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,c=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==c?void 0:c.line1,address_line_2:null==c?void 0:c.line2,city:null==c?void 0:c.city,state:null==c?void 0:c.state,country_code:null==c?void 0:c.countryCode,postal_code:null==c?void 0:c.postalCode}}function fu(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var hu=function(){return hu=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?o:i[0]:"en_us"}const Ru=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new Ro('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new Qn(Kn.MissingPaymentMethod);var o={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ku(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(o)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,o=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new Qn(Kn.MissingPaymentMethod);if(!o)throw new Ro("Unable to retrieve store configuration");var i=document.createElement("input");if(i.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",c=r.initializationData.checkoutId,u=["locale=".concat(ku(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(c)];i.src=["https://".concat(a,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),u.join("&")].join("?")}else i.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(i),i.addEventListener("click",this._handleWalletButtonClick),i},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new Qn(Kn.MissingCheckout);if(!n)throw new Qn(Kn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat("cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new ti(Xo.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Uo],t.prototype,"_handleWalletButtonClick",null),t}();var Du=function(){return Du=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===Lu()&&qu.warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var c=a[0];if(c&&c.token)return c.token;if(this._useFallback){var u=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(u)return u}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const Gu=ju;var Vu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Hu=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Vu(e,t),e}(u);var Yu,Wu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(Yu||(Yu={}));const Ku=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Yu.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Yu.MissingCart:return"Unable to proceed because cart data is unavailable.";case Yu.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Yu.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Yu.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Yu.MissingCheckoutConfig:case Yu.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Yu.MissingOrder:return"Unable to proceed because order data is unavailable.";case Yu.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Yu.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Yu.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Yu.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Yu.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return Wu(e,t),e}(u);function Zu(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,C.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function Qu(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Ju,Xu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Ju||(Ju={}));const $u=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Ju.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Ju.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Ju.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Ju.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return Xu(e,t),e}(u);var ts,es,ns,rs,os,is,as={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(ts||(ts={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(es||(es={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(ns||(ns={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(rs||(rs={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(os||(os={})),function(t){t.C0001="C0001"}(is||(is={}));var cs=function(){return cs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:s,merchantCapabilities:p,supportedNetworks:f,lineItems:[],total:h?{label:c,amount:"".concat(e.grandTotal.toFixed(d)),type:"pending"}:{label:c,amount:"".concat(e.grandTotal.toFixed(d)),type:"final"}};if(h)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(d))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(d))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return Xs(r,void 0,void 0,(function(){var r;return $s(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return Xs(r,void 0,void 0,(function(){return $s(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return Xs(r,void 0,void 0,(function(){var t;return $s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Hs;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return Xs(this,void 0,void 0,(function(){var n,r;return $s(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Ku(Yu.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new ms;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Ku(Yu.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return Xs(this,void 0,void 0,(function(){var o,i,a,c,u,s,d,l,p,f,h,y;return $s(this,(function(m){switch(m.label){case 0:o=this._transformContactToAddress(n.shippingContact),m.label=1;case 1:return m.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return m.sent(),[3,4];case 3:throw m.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,c=i.getCheckoutOrThrow(),u=null===(r=c.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,s=c.consignments[0].availableShippingOptions,d=null==s?void 0:s.find((function(t){return t.id===u})),l=null==s?void 0:s.filter((function(t){return t.id!==u})),p=d?[{label:d.description,amount:"".concat(d.cost.toFixed(a)),detail:d.additionalDescription,identifier:d.id}]:[],l&&td(td([],l.filter((function(t){return t.isRecommended})),!0),l.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(s instanceof Array))throw new Error("Shipping options not available.");if(0===s.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(c.grandTotal.toFixed(a))},[]),[2];f=s.find((function(t){return t.isRecommended})),h=f?f.id:s[0].id,y=d?d.id:h,m.label=5;case 5:return m.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return m.sent(),[3,8];case 7:throw m.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),c=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(c.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(c,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return Xs(this,void 0,void 0,(function(){var r,o,i,a;return $s(this,(function(c){switch(c.label){case 0:r=n.shippingMethod.identifier,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return c.sent(),[3,4];case 3:throw c.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return Xs(this,void 0,void 0,(function(){return $s(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return Xs(this,void 0,void 0,(function(){var n;return $s(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return Xs(this,void 0,void 0,(function(){var o,i,a,c,u,s,d,l,p,f,h,y,m;return $s(this,(function(g){switch(g.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,c=o.shippingContact,u=this._paymentIntegrationService.getState(),s=u.getCartOrThrow(),d=s.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Ys.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:l=g.sent(),g.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:l,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},f=this._transformContactToAddress(a),h=this._transformContactToAddress(c),y=null==c?void 0:c.emailAddress,m=(null==c?void 0:c.phoneNumber)||"",g.label=3;case 3:return g.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Js(Js({},f),{email:y,phone:m}))];case 4:return g.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,6];case 5:g.sent(),g.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return g.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw g.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return Xs(this,void 0,void 0,(function(){return $s(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return Xs(this,void 0,void 0,(function(){var t,e;return $s(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Ys.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Ys.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const nd=ed,rd=hs((function(t){var e=t.getState().getHost;return new nd((0,r.createRequestSender)({host:e()}),t,new Ks,new Gs(new Fc((0,Rr.getScriptLoader)(),window)))}),[{id:"applepay"}]),od=require("query-string");var id=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const ad=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return id(e,t),e}(u);var cd,ud,sd;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(cd||(cd={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(ud||(ud={})),function(t){t.Pill="pill",t.Rect="rect"}(sd||(sd={}));var dd=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,c,u,s,d,l,p,f;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const Sd=wd,Cd=hs((function(t){var e=window,n=new Gs(new Fc((0,Rr.getScriptLoader)(),e));return new Sd(t,(0,o.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function Id(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,c=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==c?void 0:c.line1,address_line_2:null==c?void 0:c.line2,city:null==c?void 0:c.city,state:null==c?void 0:c.state,country_code:null==c?void 0:c.countryCode,postal_code:null==c?void 0:c.postalCode}}function Ed(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var Od=function(){return Od=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([Uo],t)}();var zd,xd,Ud,Fd,Bd,qd,jd,Gd;function Vd(t){return t in qd}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(zd||(zd={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(xd||(xd={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Ud||(Ud={})),function(t){t.pill="pill",t.rect="rect"}(Fd||(Fd={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Bd||(Bd={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(qd||(qd={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(jd||(jd={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Gd||(Gd={}));var Hd=function(){return Hd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0))},t.prototype._mapToAddressRequestBody=function(t,e,n){var r=t.name,o=t.address1,i=t.address2,a=t.address3,c=t.locality,u=t.administrativeArea,s=t.countryCode,d=t.postalCode,l=t.phoneNumber,p=this._getFirstAndLastName(r);return{firstName:p[0],lastName:p[1],company:e,address1:o,address2:"".concat(i," ").concat(a).trim(),city:c||u,stateOrProvince:u,stateOrProvinceCode:u,countryCode:s,postalCode:d,phone:l||n,customFields:[]}},t.prototype._getFirstAndLastName=function(t){var e=t.split(" ");return 1===e.length?[t,""]:[e.slice(0,-1).join(" "),e[e.length-1]]},t.prototype._getCurrencyCodeOrThrow=function(){return Qu(this._currencyCode,(function(){return new Hu('Unable to initialize payment because "options.currencyCode" argument is not provided.')}))},t.prototype._getGooglePayShippingOption=function(t){var e,n=t.id,r=t.cost;return{id:n,label:t.description,description:(null===(e=this._currencyService)||void 0===e?void 0:e.toCustomerCurrency(r))||r}},t}();const Zd=Kd;var Qd=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Jd=function(){return Jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":D.length>0?D:void 0,commit:_,components:Al(Al(["buttons","hosted-fields","messages","payment-fields","legal"],N,!0),I,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":d,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=El(El({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const kl=Tl,Rl=hs((function(t){return new sl(t,new hl(vl(),new Il(t,new kl((0,Rr.getScriptLoader)())),(0,r.createRequestSender)(),(0,o.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]),Dl=hs((function(t){var e=(0,r.createRequestSender)();return new sl(t,new hl(vl(),new Zd("adyen",t),e,(0,o.createFormPoster)()))}),[{id:"googlepayadyenv2"}]),Ml=hs((function(t){var e=(0,r.createRequestSender)();return new sl(t,new hl(vl(),new Zd("adyen",t),e,(0,o.createFormPoster)()))}),[{id:"googlepayadyenv3"}]);var Nl=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ll=function(t){function e(e){return t.call(this,"authorizenet",e)||this}return Nl(e,t),e.prototype.mapToExternalCheckoutData=function(e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const Lp=Np;var zp=function(){return zp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?N:void 0,"disable-funding":M.length>0?M:void 0,commit:_,components:Vp(Vp(["buttons","hosted-fields","payment-fields","legal"],R,!0),D,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":d,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=qp(qp({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Yp=Hp,Wp=function(t){var e=t.getState().getHost;return new Lp((0,o.createFormPoster)(),t,new Bp((0,r.createRequestSender)({host:e()})),new Yp((0,Rr.getScriptLoader)()))};var Kp=function(){return Kp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return d.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:d.sent(),d.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return d.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return d.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=d.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Zp(this,void 0,void 0,(function(){var e,n,r;return Qp(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Zp(this,void 0,void 0,(function(){var e,n;return Qp(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const Xp=Jp,$p=hs((function(t){return new Xp(t,Wp(t))}),[{id:"paypalcommerce"}]);var tf=function(){return tf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?f:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},u&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":c,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Ku(Yu.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,c=n.buyerCountry;return{options:tf({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=tf(tf({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const of=rf,af=function(t){var e=t.styles,n={};return e.color&&(n.color=e.color),e.layout&&(n.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(n.logo={},e["logo-type"]&&(n.logo.type=e["logo-type"]),e["logo-position"]&&(n.logo.position=e["logo-position"])),e.ratio&&(n.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(n.text={},e["text-color"]&&(n.text.color=e["text-color"]),e["text-size"]&&(n.text.size=+e["text-size"])),n};var cf=function(){return cf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return d.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:d.sent(),d.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return d.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return d.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=d.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return uf(this,void 0,void 0,(function(){var e,n,r;return sf(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return uf(this,void 0,void 0,(function(){var e,n;return sf(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?af(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const lf=df,pf=hs((function(t){return new lf(t,Wp(t),new of((0,Rr.createScriptLoader)()))}),[{id:"paypalcommercecredit"}]);var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]{"use strict";var t={n:e=>{var n=e&&e.__esModule?()=>e.default:()=>e;return t.d(n,{a:n}),n},d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{createCheckoutButtonInitializer:()=>Ff,createTimeout:()=>r.createTimeout});var n={};t.r(n),t.d(n,{createAmazonPayV2ButtonStrategy:()=>Rs,createApplePayButtonStrategy:()=>rd,createBoltButtonStrategy:()=>gd,createBraintreeVenmoButtonStrategy:()=>Dd,createBraintreeVisaCheckoutButtonStrategy:()=>Cd,createGooglePayAdyenV2ButtonStrategy:()=>Dl,createGooglePayAdyenV3ButtonStrategy:()=>Ml,createGooglePayAuthorizeDotNetButtonStrategy:()=>xl,createGooglePayBraintreeButtonStrategy:()=>bl,createGooglePayCheckoutComButtonStrategy:()=>Hl,createGooglePayCybersourceButtonStrategy:()=>Zl,createGooglePayOrbitalButtonStrategy:()=>$l,createGooglePayPayPalCommerceButtonStrategy:()=>Rl,createGooglePayStripeButtonStrategy:()=>pp,createGooglePayTdOnlineMartButtonStrategy:()=>Sp,createGooglePayWorldpayAccessButtonStrategy:()=>mp,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>If,createPayPalCommerceButtonStrategy:()=>$p,createPayPalCommerceCreditButtonStrategy:()=>pf,createPayPalCommerceVenmoButtonStrategy:()=>vf,createPaypalExpressButtonStrategy:()=>Uf});const r=require("@bigcommerce/request-sender"),o=require("@bigcommerce/form-poster"),i=require("@bigcommerce/data-store");var a,c=(a=function(t,e){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},a(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const u=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return c(e,t),e}(Error);var s=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),d={body:{},headers:{},status:0},l=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,c=e||d,u=c.body,s=c.headers,l=c.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=s,a.status=l,a.errors=i||[],a}return s(e,t),e}(u);const p=l;var f=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const h=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return f(e,t),e}(p);var y=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return y(e,t),e}(Error);var g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),v={body:{},headers:{},status:0},b=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,c=e||v,u=c.body,s=c.headers,d=c.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=s,a.status=d,a.errors=i||[],a}return g(e,t),e}(m);const _=b;var w=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const S=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return w(e,t),e}(_),C=require("lodash");var I=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0}})),W=$n(F,(function(t){return function(e){return!(!e||!e.nonce)||t()===ur||t()===sr}})),(0,Wn.memoizeOne)((function(t,e){return{getPaymentId:x({checkout:t,order:e}),getPaymentIdOrThrow:U({checkout:t,order:e}),getPaymentStatus:F({checkout:t,order:e}),getPaymentStatusOrThrow:B({checkout:t,order:e}),getPaymentToken:q({checkout:t,order:e}),getPaymentTokenOrThrow:j({checkout:t,order:e}),getPaymentRedirectUrl:G({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:V({checkout:t,order:e}),isPaymentDataRequired:H({checkout:t,order:e}),isPaymentDataSubmitted:W({checkout:t,order:e})}}))),Et=function(){var t=$n((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=$n((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,Wn.memoizeOne)((function(n){return void 0===n&&(n=pr),{getApplyError:t(n),isApplying:e(n)}}))}(),Ot=function(){var t=$n((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=$n((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,Wn.memoizeOne)((function(n){return void 0===n&&(n=Un),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Pt=(K=$n((function(t){return t.data}),(function(t){return function(){return t}})),Z=$n((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),Q=$n((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,Wn.memoizeOne)((function(t){return void 0===t&&(t=An),{getEmail:K(t),getSendError:Z(t),isSending:Q(t)}}))),At=function(){var t=$n((function(t){return t.data}),(function(t){return function(){return t}})),e=$n((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=$n((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=$n((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,Wn.memoizeOne)((function(o){return void 0===o&&(o=Zt),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n,r=J(t.billingAddress),o=X(t.cart),i=$(t.checkoutButton),a=et(t.countries),c=nt(t.coupons),u=rt(t.customer),s=it(t.customerStrategies),d=At(t.extensions),l=ut(t.formFields),p=at(t.giftCertificates),f=ct(t.instruments),h=St(t.orderBillingAddress),y=st(t.paymentMethods),m=ft(t.paymentProviderCustomer),g=lt(t.paymentStrategies),v=pt(t.pickupOptions),b=ht(t.remoteCheckout),_=yt(t.consignments),w=mt(t.shippingCountries),S=gt(t.shippingStrategies),C=Ot(t.subscriptions),I=Et(t.storeCredit),E=Pt(t.signInEmail),O=vt(t.consignments,o),P=_t(t.checkout,r,o,O,c,u,p),A=wt(t.order,h,c),T=Ct(P,A),k={billingAddress:r,cart:o,checkout:P,checkoutButton:i,config:tt(t.config,t.formFields),consignments:O,countries:a,coupons:c,customer:u,customerStrategies:s,extensions:d,form:l,giftCertificates:p,instruments:f,order:A,orderBillingAddress:h,payment:T,paymentMethods:y,paymentProviderCustomer:m,paymentStrategies:g,pickupOptions:v,remoteCheckout:b,shippingAddress:_,shippingCountries:w,shippingStrategies:S,signInEmail:E,subscriptions:C,storeCredit:I};return e.shouldWarnMutation?(n=k,Object.keys(n).reduce((function(t,e){return t[e]=rr(n[e]),t}),{})):k}}var yr=function(){return yr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadPaymentMethod",null),t}();const Cr=Sr;var Ir;!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(Ir||(Ir={}));const Er=Ir;var Or="This API endpoint is for internal use only and may change in the future",Pr={"X-Checkout-SDK-Version":"1.696.0"},Ar=function(){return Ar=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new to(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,c="/api/storefront/checkout/".concat(t),u=eo({Accept:Er.JsonV1},Pr);return this._requestSender.put(c,{params:{include:Jr(Xr,i)},body:e,headers:u,timeout:a})},t}();const ro=no,oo=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,C.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return"".concat(t.id).localeCompare("".concat(e.id))})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}();var io=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const ao=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return io(e,t),e}(m),co=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new Qn(Kn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new oo;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new ao(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,C.isEqual)((0,C.map)(t,"code"),(0,C.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,C.isEqual)((0,C.map)(t,"code"),(0,C.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,o=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:o}},t}();const uo=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return M.Observable.create((function(n){n.next((0,i.createAction)(st.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,i.createAction)(st.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,i.createErrorAction)(st.LoadConfigFailed,t))}))}))},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadConfig",null),t}();var so=function(){return so=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new to(t);throw t}))},t}();const po=lo;function fo(t){var e=t;return"object"==typeof e&&"object"==typeof e.payload&&"string"==typeof e.payload.token}var ho=function(){return ho=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([br],t.prototype,"loadFormFields",null),t}();const _o=bo;var wo=function(){return wo=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&Mo(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Uo],t.prototype,"_handleMessage",null),t}();const qo=Bo;var jo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Go=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return jo(e,t),e}(m);var Vo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Ho=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return Vo(e,t),e}(m);var Yo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Wo=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return Yo(e,t),e}(m);var Ko=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function c(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,c)}u((r=r.apply(t,e||[])).next())}))},Zo=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!c?a:"".concat(a," ").concat("/"," ").concat(c)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const ra=na,oa=require("card-validator"),ia=function(){function t(){}return t.prototype.format=function(t){var e=(0,oa.number)(t).card;if(!e)return t;var n=(0,C.max)((0,oa.creditCardType)(t).map((function(t){return(0,C.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,oa.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();var aa=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new Qn(Kn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,C.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"==typeof t&&"address"in t},t}();const Oa=Ea;var Pa=function(){return Pa=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([_c],t)}();const Sc=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([_c],t)}();function Cc(t){return{errors:new wc(t),statuses:new Sc(t)}}var Ic=function(){return Ic=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([Uo],t)}();const Oc=Ec;var Pc=function(){return Pc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t}function pu(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,c=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==c?void 0:c.line1,address_line_2:null==c?void 0:c.line2,city:null==c?void 0:c.city,state:null==c?void 0:c.state,country_code:null==c?void 0:c.countryCode,postal_code:null==c?void 0:c.postalCode}}function fu(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var hu=function(){return hu=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?o:i[0]:"en_us"}const Ru=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new Ro('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new Qn(Kn.MissingPaymentMethod);var o={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ku(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(o)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,o=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new Qn(Kn.MissingPaymentMethod);if(!o)throw new Ro("Unable to retrieve store configuration");var i=document.createElement("input");if(i.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",c=r.initializationData.checkoutId,u=["locale=".concat(ku(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(c)];i.src=["https://".concat(a,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),u.join("&")].join("?")}else i.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(i),i.addEventListener("click",this._handleWalletButtonClick),i},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new Qn(Kn.MissingCheckout);if(!n)throw new Qn(Kn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat("cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new ti(Xo.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Uo],t.prototype,"_handleWalletButtonClick",null),t}();var Du=function(){return Du=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===Lu()&&qu.warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var c=a[0];if(c&&c.token)return c.token;if(this._useFallback){var u=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(u)return u}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const Gu=ju;var Vu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Hu=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Vu(e,t),e}(u);var Yu,Wu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(Yu||(Yu={}));const Ku=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Yu.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Yu.MissingCart:return"Unable to proceed because cart data is unavailable.";case Yu.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Yu.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Yu.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Yu.MissingCheckoutConfig:case Yu.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Yu.MissingOrder:return"Unable to proceed because order data is unavailable.";case Yu.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Yu.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Yu.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Yu.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Yu.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return Wu(e,t),e}(u);function Zu(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,C.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function Qu(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Ju,Xu=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Ju||(Ju={}));const $u=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Ju.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Ju.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Ju.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Ju.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return Xu(e,t),e}(u);var ts,es,ns,rs,os,is,as={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(ts||(ts={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(es||(es={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(ns||(ns={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(rs||(rs={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(os||(os={})),function(t){t.C0001="C0001"}(is||(is={}));var cs=function(){return cs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:s,merchantCapabilities:p,supportedNetworks:f,lineItems:[],total:h?{label:c,amount:"".concat(e.grandTotal.toFixed(d)),type:"pending"}:{label:c,amount:"".concat(e.grandTotal.toFixed(d)),type:"final"}};if(h)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(d))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(d))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return Xs(r,void 0,void 0,(function(){var r;return $s(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return Xs(r,void 0,void 0,(function(){return $s(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return Xs(r,void 0,void 0,(function(){var t;return $s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Hs;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return Xs(r,void 0,void 0,(function(){return $s(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return Xs(this,void 0,void 0,(function(){var n,r;return $s(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Ku(Yu.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new ms;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Ku(Yu.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return Xs(this,void 0,void 0,(function(){var o,i,a,c,u,s,d,l,p,f,h,y;return $s(this,(function(m){switch(m.label){case 0:o=this._transformContactToAddress(n.shippingContact),m.label=1;case 1:return m.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return m.sent(),[3,4];case 3:throw m.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,c=i.getCheckoutOrThrow(),u=null===(r=c.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,s=c.consignments[0].availableShippingOptions,d=null==s?void 0:s.find((function(t){return t.id===u})),l=null==s?void 0:s.filter((function(t){return t.id!==u})),p=d?[{label:d.description,amount:"".concat(d.cost.toFixed(a)),detail:d.additionalDescription,identifier:d.id}]:[],l&&td(td([],l.filter((function(t){return t.isRecommended})),!0),l.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(s instanceof Array))throw new Error("Shipping options not available.");if(0===s.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(c.grandTotal.toFixed(a))},[]),[2];f=s.find((function(t){return t.isRecommended})),h=f?f.id:s[0].id,y=d?d.id:h,m.label=5;case 5:return m.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return m.sent(),[3,8];case 7:throw m.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),c=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(c.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(c,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return Xs(this,void 0,void 0,(function(){var r,o,i,a;return $s(this,(function(c){switch(c.label){case 0:r=n.shippingMethod.identifier,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return c.sent(),[3,4];case 3:throw c.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return Xs(this,void 0,void 0,(function(){return $s(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return Xs(this,void 0,void 0,(function(){var n;return $s(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return Xs(this,void 0,void 0,(function(){var o,i,a,c,u,s,d,l,p,f,h,y,m;return $s(this,(function(g){switch(g.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,c=o.shippingContact,u=this._paymentIntegrationService.getState(),s=u.getCartOrThrow(),d=s.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Ys.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:l=g.sent(),g.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:l,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},f=this._transformContactToAddress(a),h=this._transformContactToAddress(c),y=null==c?void 0:c.emailAddress,m=(null==c?void 0:c.phoneNumber)||"",g.label=3;case 3:return g.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Js(Js({},f),{email:y,phone:m}))];case 4:return g.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,6];case 5:g.sent(),g.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return g.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw g.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return Xs(this,void 0,void 0,(function(){return $s(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return Xs(this,void 0,void 0,(function(){var t,e;return $s(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Ys.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Ys.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const nd=ed,rd=hs((function(t){var e=t.getState().getHost;return new nd((0,r.createRequestSender)({host:e()}),t,new Ks,new Gs(new Fc((0,Rr.getScriptLoader)(),window)))}),[{id:"applepay"}]),od=require("query-string");var id=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const ad=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return id(e,t),e}(u);var cd,ud,sd;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(cd||(cd={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(ud||(ud={})),function(t){t.Pill="pill",t.Rect="rect"}(sd||(sd={}));var dd=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,c,u,s,d,l,p,f;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const Sd=wd,Cd=hs((function(t){var e=window,n=new Gs(new Fc((0,Rr.getScriptLoader)(),e));return new Sd(t,(0,o.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function Id(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,c=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==c?void 0:c.line1,address_line_2:null==c?void 0:c.line2,city:null==c?void 0:c.city,state:null==c?void 0:c.state,country_code:null==c?void 0:c.countryCode,postal_code:null==c?void 0:c.postalCode}}function Ed(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var Od=function(){return Od=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;c--)(o=t[c])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([Uo],t)}();var zd,xd,Ud,Fd,Bd,qd,jd,Gd;function Vd(t){return t in qd}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(zd||(zd={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(xd||(xd={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Ud||(Ud={})),function(t){t.pill="pill",t.rect="rect"}(Fd||(Fd={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Bd||(Bd={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(qd||(qd={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(jd||(jd={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Gd||(Gd={}));var Hd=function(){return Hd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0))},t.prototype._mapToAddressRequestBody=function(t,e,n){var r=t.name,o=t.address1,i=t.address2,a=t.address3,c=t.locality,u=t.administrativeArea,s=t.countryCode,d=t.postalCode,l=t.phoneNumber,p=this._getFirstAndLastName(r);return{firstName:p[0],lastName:p[1],company:e,address1:o,address2:"".concat(i," ").concat(a).trim(),city:c||u,stateOrProvince:u,stateOrProvinceCode:u,countryCode:s,postalCode:d,phone:l||n,customFields:[]}},t.prototype._getFirstAndLastName=function(t){var e=t.split(" ");return 1===e.length?[t,""]:[e.slice(0,-1).join(" "),e[e.length-1]]},t.prototype._getCurrencyCodeOrThrow=function(){return Qu(this._currencyCode,(function(){return new Hu('Unable to initialize payment because "options.currencyCode" argument is not provided.')}))},t.prototype._getGooglePayShippingOption=function(t){var e,n=t.id,r=t.cost;return{id:n,label:t.description,description:(null===(e=this._currencyService)||void 0===e?void 0:e.toCustomerCurrency(r))||r}},t}();const Zd=Kd;var Qd=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Jd=function(){return Jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":D.length>0?D:void 0,commit:_,components:Al(Al(["buttons","hosted-fields","messages","payment-fields","legal"],N,!0),I,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":d,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=El(El({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const kl=Tl,Rl=hs((function(t){return new sl(t,new hl(vl(),new Il(t,new kl((0,Rr.getScriptLoader)())),(0,r.createRequestSender)(),(0,o.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]),Dl=hs((function(t){var e=(0,r.createRequestSender)();return new sl(t,new hl(vl(),new Zd("adyen",t),e,(0,o.createFormPoster)()))}),[{id:"googlepayadyenv2"}]),Ml=hs((function(t){var e=(0,r.createRequestSender)();return new sl(t,new hl(vl(),new Zd("adyen",t),e,(0,o.createFormPoster)()))}),[{id:"googlepayadyenv3"}]);var Nl=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ll=function(t){function e(e){return t.call(this,"authorizenet",e)||this}return Nl(e,t),e.prototype.mapToExternalCheckoutData=function(e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const Lp=Np;var zp=function(){return zp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?N:void 0,"disable-funding":M.length>0?M:void 0,commit:_,components:Vp(Vp(["buttons","hosted-fields","payment-fields","legal"],R,!0),D,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":d,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=qp(qp({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Yp=Hp,Wp=function(t){var e=t.getState().getHost;return new Lp((0,o.createFormPoster)(),t,new Bp((0,r.createRequestSender)({host:e()})),new Yp((0,Rr.getScriptLoader)()))};var Kp=function(){return Kp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return d.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:d.sent(),d.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return d.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return d.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=d.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Zp(this,void 0,void 0,(function(){var e,n,r;return Qp(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Zp(this,void 0,void 0,(function(){var e,n;return Qp(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const Xp=Jp,$p=hs((function(t){return new Xp(t,Wp(t))}),[{id:"paypalcommerce"}]);var tf=function(){return tf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?f:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},u&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":c,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Ku(Yu.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,c=n.buyerCountry;return{options:tf({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":c}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=tf(tf({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const of=rf,af=function(t){var e=t.styles,n={};return e.color&&(n.color=e.color),e.layout&&(n.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(n.logo={},e["logo-type"]&&(n.logo.type=e["logo-type"]),e["logo-position"]&&(n.logo.position=e["logo-position"])),e.ratio&&(n.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(n.text={},e["text-color"]&&(n.text.color=e["text-color"]),e["text-size"]&&(n.text.size=+e["text-size"])),n};var cf=function(){return cf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return d.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:d.sent(),d.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return d.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return d.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=d.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return uf(this,void 0,void 0,(function(){var e,n,r;return sf(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return uf(this,void 0,void 0,(function(){var e,n;return sf(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?af(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const lf=df,pf=hs((function(t){return new lf(t,Wp(t),new of((0,Rr.createScriptLoader)()))}),[{id:"paypalcommercecredit"}]);var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1](()=>{var t={22723:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(95757)),i=l(n(61461)),a=l(n(20501)),u=l(n(22682)),c=l(n(33697)),s=l(n(98610));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,e.default={host:""}},88604:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},55739:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(88604),o=n(40816),i={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:o.GET};e.default=i},40816:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},71249:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(88477),n(14718),n(57188),n(62342),n(25226),n(13521),n(35157),n(25766),n(53618),n(11062),n(948),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=(o=n(95757))&&o.__esModule?o:{default:o},a=n(88604),u=n(30390);function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,u.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,o=t.statusText,i="response"in t?t.response:t.responseText;return i&&(0,u.includes)(n,a.APPLICATION_JSON)&&(i=JSON.parse(i)),{data:i,headers:e,status:r,statusText:o}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,i.default)({},t,function(t,e,n){return(e=l(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&s(e.prototype,n),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},24475:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(65778)),i=l(n(95757)),a=n(40816),u=l(n(55739)),c=l(n(71249)),s=l(n(24475));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n=200&&t.status<300}}])&&p(e.prototype,n),r&&p(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},36421:(t,e,n)=>{"use strict";n(47818),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},30390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return f.default}});var r=p(n(36421)),o=p(n(40570)),i=p(n(67522)),a=p(n(67150)),u=p(n(59731)),c=p(n(41207)),s=p(n(29503)),l=p(n(50377)),f=p(n(31887));function p(t){return t&&t.__esModule?t:{default:t}}},45212:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},46885:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,o.default)(t)};var r=i(n(45212)),o=i(n(40570));function i(t){return t&&t.__esModule?t:{default:t}}},40570:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},67522:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===o(t)&&!Array.isArray(t)}},67150:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(46885)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},59731:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(40570)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},41207:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,o.default)(t)?Object.keys(t).reduce((function(n,r){var o=t[r];return e(o)||(n[r]=o),n}),{}):t};var r,o=(r=n(67522))&&r.__esModule?r:{default:r}},29503:(t,e,n)=>{"use strict";n(8933),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},50377:(t,e,n)=>{"use strict";n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},31887:(t,e,n)=>{"use strict";n(25226),n(69204),n(13521),n(88315),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},34936:(t,e,n)=>{"use strict";e.U=function(t){return o.default.create(t)};var r,o=(r=n(22723))&&r.__esModule?r:{default:r}},22682:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=u(n(84916)),i=u(n(39835)),a=u(n(76473));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(74152),i=n(92299),a=c(n(87730)),u=c(n(76473));function c(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e,n){return(e=c(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=f(n(95757)),i=n(30390),a=f(n(77140)),u=f(n(84094)),c=f(n(65245)),s=f(n(69465)),l=f(n(27231));function f(t){return t&&t.__esModule?t:{default:t}}function p(t){return p="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},p(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE_ACCELERATED_CHECKOUT=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.BRAINTREE_ACCELERATED_CHECKOUT="braintreeacceleratedcheckout",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT="paypalcommerceacceleratedcheckout",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},69465:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(6073),i=n(34526);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},20501:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=s(n(84916)),i=n(92299),a=s(n(18581)),u=s(n(46833)),c=s(n(76473));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},46833:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=n(6073);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=s(n(64003)),a=s(n(85195)),u=s(n(67093)),c=s(n(16620));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=u(n(95757)),i=n(30390),a=u(n(69465));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=s(n(72052)),a=s(n(33018)),u=s(n(88124)),c=s(n(86883));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=n(30390),a=(o=n(69465))&&o.__esModule?o:{default:o};function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=c(n(84916)),i=n(40816),a=c(n(93684)),u=n(91486);function c(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";n(80404),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,i,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},u=a.providerName,c=a.defaultInstrument,s=(0,r.omitNil)({name:u});return(0,r.omitNil)({provider:s,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,i=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:i})),billing_address:o(a.billingAddress),default_instrument:c})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return o(t)}))}):(0,r.omitNil)({shipping_address:o(t.shippingAddress)})};var r=n(30390);function o(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:o})}},2467:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function(t,e){var n=(e||{}).equalityCheck,i=void 0===n?o:n;return function(e,n){return Object.keys(t).reduce((function(o,a){var u,c=t[a],s=e?e[a]:void 0,l=c(s,n);return i(s,l)&&o?o:r.assign({},o,((u={})[a]=l,u))}),e||{})}}},19492:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(44396),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(96150);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(45550);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},o.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},69199:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2467),o=n(56498);e.default=function(t,e,n){return"function"==typeof t?new o.default(t,e,n):new o.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},69776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(49997);e.default=function(t,e,n){return r.__assign({},o.default(t,e,n),{error:!0})}},56498:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(87218),u=n(57532),c=n(96150),s=n(45926),l=n(2557),f=n(12079),p=n(64472),d=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=o.__assign({actionTransformer:f.default,equalityCheck:c,shouldWarnMutation:!0,stateTransformer:p.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(u.mergeMap((function(t){return t.pipe(u.concatMap((function(t){return t})))})),u.filter((function(t){return!!t.type})),u.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),u.distinctUntilChanged((function(t,e){var n=t.state,o=e.state;return r._options.equalityCheck(n,o)})),u.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return l.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],o=1;o0&&(c=c.pipe(u.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),i&&!1===i.initial&&(c=c.pipe(u.skip(1)));var s=[c.subscribe(t),this._notification$.subscribe(t)];return function(){return s.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):s.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,o){var c=n._getDispatchError(e.queueId),s=n._options.actionTransformer(a.from(t).pipe(u.map((function(t){return e.queueId?i.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(s).pipe(u.map((function(t,e){return 0===e&&c.pipe(u.first()).subscribe(o),t.error&&o(t.payload),t})),u.catchError((function(t){return o(t instanceof Error?t:t.payload),a.of(t)})),u.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=d},45926:(t,e,n)=>{"use strict";n(80404),n(56949),n(32194),n(38085),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function t(e,n){try{var i=n||{},a=i.equalityCheck,u=void 0===a?o:a,c=i.previousValue,s=void 0===c?null:c;return u(e,s)&&Object.isFrozen(s)?s:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:u,previousValue:Array.isArray(s)?s[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:u,previousValue:s&&s.hasOwnProperty(r)?s[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},99840:(t,e,n)=>{"use strict";n(56498).default;var r=n(2467);e.HY=r.default;var o=n(19492);e.om=o.default;var i=n(49997);e.VP=i.default;var a=n(69199);e.iN=a.default;var u=n(69776);e.fQ=u.default;var c=n(45926);e.ol=c.default},2557:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},12079:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},64472:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},83736:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>w,__asyncGenerator:()=>_,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>f,__classPrivateFieldGet:()=>O,__classPrivateFieldSet:()=>P,__createBinding:()=>d,__decorate:()=>c,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>s,__read:()=>v,__rest:()=>u,__spread:()=>m,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(i=t[c])&&(u=(a<3?i(u):a>3?i(e,n,u):i(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function s(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function f(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function m(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(c,s):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function c(t){u("next",t)}function s(t){u("throw",t)}function l(t,e){t(e),i.shift(),i.length&&u(i[0][0],i[0][1])}}function w(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function O(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function P(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},21887:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(60834),o=n(33788);e.default=function(t){var e=new r.default;return new o.default(e,t)}},60834:(t,e,n)=>{"use strict";n(21894),n(44594),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,o=document.createElement("form");return o.style.display="none",o.setAttribute("action",t),o.setAttribute("method","POST"),o.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];o.appendChild(r._createInput(n,t))})),o},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},33788:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(12789),o=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var o=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(o),o.submit()},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!(0,r.isAbsoluteUrl)(t)?(0,r.joinPaths)(this._options.host,t):t},t}();e.default=o},74152:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FormPoster=e.createFormPoster=void 0;var r=n(21887);Object.defineProperty(e,"createFormPoster",{enumerable:!0,get:function(){return r.default}});var o=n(33788);Object.defineProperty(e,"FormPoster",{enumerable:!0,get:function(){return o.default}})},12789:(t,e,n)=>{"use strict";n(98556),n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.joinPaths=e.isAbsoluteUrl=void 0,e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return"".concat((n=t,n.replace(/\/$/,"")),"/").concat(function(t){return t.replace(/^\//,"")}(e));var n}},89998:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},26879:(t,e,n)=>{"use strict";n(47818),n(80404),n(44396),n(67068),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=n(45550),i=r.__importDefault(n(96150)),a=n(89998),u=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:i.default,maxSize:0,onExpire:o.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(71652);e.Bj=r.default,e.B4=r.memoizeOne},71652:(t,e,n)=>{"use strict";n(14718),n(20363),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=r.__importDefault(n(59745)),i=r.__importDefault(n(96150)),a=r.__importDefault(n(26879));function u(t,e){var n=r.__assign({maxSize:0,isEqual:i.default},e),u=n.maxSize,c=n.isEqual,s=new Map,l=new a.default({isEqual:c,maxSize:u,onExpire:function(t){return s.delete(t)}}),f=o.default(t,(function(){for(var t=[],e=0;e{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>w,__asyncGenerator:()=>_,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>f,__classPrivateFieldGet:()=>O,__classPrivateFieldSet:()=>P,__createBinding:()=>d,__decorate:()=>c,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>s,__read:()=>v,__rest:()=>u,__spread:()=>m,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(i=t[c])&&(u=(a<3?i(u):a>3?i(e,n,u):i(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function s(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function f(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function m(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(c,s):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function c(t){u("next",t)}function s(t){u("throw",t)}function l(t,e){t(e),i.shift(),i.length&&u(i[0][0],i[0][1])}}function w(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function O(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function P(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},78163:(t,e,n)=>{"use strict";n.d(e,{g:()=>o}),n(21894);var r=n(43419),o=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.As(e)},t}()},60931:(t,e,n)=>{"use strict";n.d(e,{A:()=>u});var r=n(77650),o=n(39649),i=n(30187),a=n(71844);function u(t){return new a.A(new i.A,new o.A,r,t)}},33767:(t,e,n)=>{"use strict";n.d(e,{A:()=>o});var r=n(85466);function o(t){return new r.A(t)}},9285:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>i.A,Timeout:()=>a.A,createRequestSender:()=>r.A,createTimeout:()=>o.A});var r=n(60931),o=n(33767),i=n(71844),a=n(85466)},66029:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947)},39649:(t,e,n)=>{"use strict";n.d(e,{A:()=>u}),n(57188),n(53618),n(11062),n(948);var r=n(31355),o=n(38780),i=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const u=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(i.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,o.A)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&i.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,o=e.split(":"),i=(o.shift()||"").trim();return i?(0,r.Cl)((0,r.Cl)({},t),((n={})[i.toLowerCase()]=o.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},30187:(t,e,n)=>{"use strict";n.d(e,{A:()=>o}),n(14266),n(21894),n(44594);var r=n(43419);const o=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.As(e,{encode:n}):t},t}()},71844:(t,e,n)=>{"use strict";n.d(e,{A:()=>s}),n(13521),n(67536),n(84090),n(88315),n(95743),n(53618),n(11062);var r=n(31355),o=n(40117),i=n.n(o),a=n(78163),u=n(66029),c=n(85466);const s=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.g}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),o=this._getCachedRequest(t,r);if(o)return Promise.resolve(o);var i=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,o){var a=function(){var a=n._payloadTransformer.toResponse(i);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):o(a)};i.onload=a,i.onerror=a,i.onabort=a,i.ontimeout=a,r.timeout instanceof c.A&&(r.timeout.onComplete((function(){return i.abort()})),r.timeout.start()),(0,u.A)(r.timeout)&&r.timeout.then((function(){return i.abort()})),i.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&this._isLocalRequest(t)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),i()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t.prototype._isLocalRequest=function(t){return!!t.match(new RegExp("^(https?:)?//"+window.location.hostname))||!t.match(new RegExp("^(https?:)?//"))},t}()},85466:(t,e,n)=>{"use strict";n.d(e,{A:()=>r}),n(13521),n(67536);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},38780:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14266),n(14718),n(57188),n(80404),n(21894),n(13521),n(25766),n(92947)},43419:(t,e,n)=>{"use strict";n(91621),n(27481),n(90105),n(98556),n(14266),n(47818),n(14718),n(57188),n(80404),n(44396),n(18492),n(25226),n(21894),n(13521),n(25766),n(53618),n(11062),n(948),n(44594),n(92947);var r=n(23081),o=n(95757);n(88577);function i(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.As=function(t,e){!1===(e=o({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[i(e,t),"[",r,"]"].join(""):[i(e,t),"[",i(r,t),"]=",i(n,t)].join("")};case"bracket":return function(e,n){return null===n?i(e,t):[i(e,t),"[]=",i(n,t)].join("")};default:return function(e,n){return null===n?i(e,t):[i(e,t),"=",i(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var o=t[r];if(void 0===o)return"";if(null===o)return i(r,e);if(Array.isArray(o)){var a=[];return o.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return i(r,e)+"="+i(o,e)})).filter((function(t){return t.length>0})).join("&"):""}},31355:(t,e,n)=>{"use strict";n.d(e,{Cl:()=>r}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},50961:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(860);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},52904:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(79029);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},54721:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(50961);e.default=function(){return r||(r=o.default()),r}},50808:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(52904);e.default=function(){return r||(r=o.default()),r}},4993:(t,e,n)=>{"use strict";n(860).default;var r=n(50961);e.Hb=r.default;var o=n(54721);e.vQ=o.default,n(79029).default,n(52904).default,n(50808).default},860:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,o){var i=document.createElement("script"),a=e||{},u=a.async,c=void 0!==u&&u,s=a.attributes,l=void 0===s?{}:s;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onreadystatechange=function(){return r()},i.onerror=function(e){delete n._scripts[t],o(e)},i.async=c,i.src=t,document.body.appendChild(i)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var u=document.createElement("link");u.as="script",u.rel=a,u.href=t,u.onload=function(){r()},u.onerror=function(){delete n._preloadedScripts[t],o()},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(o)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},79029:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,o){var i=document.createElement("link"),a=e||{},u=a.prepend,c=void 0!==u&&u,s=a.attributes,l=void 0===s?{}:s;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onerror=function(e){delete n._stylesheets[t],o(e)},i.rel="stylesheet",i.href=t,c&&document.head.children[0]?document.head.insertBefore(i,document.head.children[0]):document.head.appendChild(i)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i,u=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(u)){var c=document.createElement("link");c.as="style",c.rel=a?"prefetch":"preload",c.href=t,c.onload=function(){r()},c.onerror=function(e){delete n._preloadedStylesheets[t],o(e)},document.head.appendChild(c)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(o)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},35647:(t,e,n)=>{"use strict";t.exports={number:n(71990),expirationDate:n(15862),expirationMonth:n(38138),expirationYear:n(62711),cvv:n(2999),postalCode:n(89333),creditCardType:n(30439)}},71990:(t,e,n)=>{"use strict";n(53618);var r=n(7759),o=n(30439);function i(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,u,c,s;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return i(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return i(null,!1,!1);if(0===(n=o(t)).length)return i(null,!1,!1);if(1!==n.length)return i(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return i(a,!1,!1);for(u=a.type===o.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),s=Math.max.apply(null,a.lengths),e.maxLength&&(s=Math.min(e.maxLength,s)),c=0;c{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},15862:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(53618),n(92947);var o=n(15410),i=n(38138),a=n(62711);function u(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,c,s,l;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=o(t);else{if(null===t||"object"!==r(t))return u(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(c=i(n.month),s=a(n.year,e),c.isValid){if(s.isCurrentYear)return u(l=c.isValidForThisYear,l,n.month,n.year);if(s.isValid)return u(!0,!0,n.month,n.year)}return c.isPotentiallyValid&&s.isPotentiallyValid?u(!1,!0,null,null):u(!1,!1,null,null)}},38138:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(17186),n(53618),t.exports=function(t){var e,n,o=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=o)):r(!1,!1)}},62711:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}n(44396),n(25226),n(17186),n(53618),t.exports=function(t,e){var n,o,i,a,u;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(o=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===o?r(!1,t.slice(0,2)===String(n).slice(0,2)):o>4?r(!1,!1):(t=parseInt(t,10),i=Number(String(n).substr(2,2)),2===o?(u=i===t,a=t>=i&&t<=i+e):4===o&&(u=n===t,a=t>=n&&t<=n+e),r(a,a,u))):r(!1,!1)}},11476:(t,e,n)=>{"use strict";n(13521),n(88315),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},7759:(t,e,n)=>{"use strict";n(17186),t.exports=function(t){for(var e,n=0,r=!1,o=t.length-1;o>=0;)e=parseInt(t.charAt(o),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,o--;return n%10==0}},15410:(t,e,n)=>{"use strict";n(57188),n(5360),n(44396),n(25226),n(11062);var r=n(62711),o=n(11476);t.exports=function(t){var e,n,i,a,u;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),o(t)?{month:t[0]||"",year:t.slice(1).join()}:(i=t,n=0===(u=Number(i[0]))?2:u>1||1===u&&Number(i[1])>2?1:1===u?(a=i.substr(1),r(a).isPotentiallyValid?1:2):5===i.length?1:i.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},89333:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(47818),n(80404),n(67068),n(21894),n(44594);var r,o=n(45237),i=n(97458),a=n(40179),u=n(84438),c=n(39187),s={},l={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},f=[l.VISA,l.MASTERCARD,l.AMERICAN_EXPRESS,l.DINERS_CLUB,l.DISCOVER,l.JCB,l.UNIONPAY,l.MAESTRO,l.ELO,l.MIR,l.HIPER,l.HIPERCARD];function p(t){return s[t]||o[t]}function d(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function h(t){var e,n=[];return u(t)?0===t.length?r.map((function(t){return i(p(t))})):(r.forEach((function(e){var r=p(e);c(t,r,n)})),(e=a(n))?[e]:n):[]}r=i(f),h.getTypeInfo=function(t){return i(p(t))},h.removeCard=function(t){var e=d(t);r.splice(e,1)},h.addCard=function(t){var e=d(t.type,!0);s[t.type]=t,-1===e&&r.push(t.type)},h.updateCard=function(t,e){var n,r=s[t]||o[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=i(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),s[n.type]=n},h.changeOrder=function(t,e){var n=d(t);r.splice(n,1),r.splice(e,0,t)},h.resetModifications=function(){r=i(f),s={}},h.types=l,t.exports=h},39187:(t,e,n)=>{"use strict";var r=n(97458),o=n(98834);t.exports=function(t,e,n){var i,a,u,c;for(i=0;i=u&&(c.matchStrength=u),n.push(c);break}}},45237:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},97458:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},40179:(t,e,n)=>{"use strict";n(14266),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},98834:(t,e,n)=>{"use strict";n(17186),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,o=t.substr(0,r),i=parseInt(o,10);return e=parseInt(String(e).substr(0,o.length),10),n=parseInt(String(n).substr(0,o.length),10),i>=e&&i<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},88577:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(98556),n(14718),n(57188),n(44396),n(21894),n(13521),n(84090),n(88315),n(25766),n(95743),n(53618),n(92947);var o="%[a-f0-9]{2}",i=new RegExp("("+o+")|([^%]+?)","gi"),a=new RegExp("("+o+")+","gi");function u(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],u(n),u(r))}function c(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(i)||[],n=1;n{"use strict";n(91621);var r=n(62034),o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(t,e,n){var i=e[n];if(null!=i){if(o.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");o.call(t,n)&&r(i)?t[n]=u(Object(t[n]),e[n]):t[n]=i}}function u(t,e){if(t===e)return t;for(var n in e=Object(e))o.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),u=0;u{"use strict";n(47818),n(21894),t.exports=function(t,e){for(var n={},r=Object.keys(t),o=Array.isArray(e),i=0;i{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947),t.exports=function(t){var e=r(t);return null!==t&&("object"===e||"function"===e)}},77650:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(57188),n(44396),n(13521),n(25766),n(53618),n(11062),n(92947),function(n){var o;if("function"==typeof define&&define.amd&&(define(n),o=!0),"object"===r(e)&&(t.exports=n(),o=!0),!o){var i=window.Cookies,a=window.Cookies=n();a.noConflict=function(){return window.Cookies=i,a}}}((function(){function t(){for(var t=0,e={};t{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(80404),n(67068),n(13521),n(84090),n(88315),n(25766),n(53618),n(92947);var o,i="__lodash_hash_undefined__",a="[object Function]",u="[object GeneratorFunction]",c=/^\[object .+?Constructor\]$/,s="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,l="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,f=s||l||Function("return this")(),p=Array.prototype,d=Function.prototype,h=Object.prototype,y=f["__core-js_shared__"],v=(o=/[^.]+$/.exec(y&&y.keys&&y.keys.IE_PROTO||""))?"Symbol(src)_1."+o:"",m=d.toString,g=h.hasOwnProperty,b=h.toString,_=RegExp("^"+m.call(g).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),w=p.splice,S=A(f,"Map"),C=A(Object,"create");function E(t){var e=-1,n=t?t.length:0;for(this.clear();++e-1},I.prototype.set=function(t,e){var n=this.__data__,r=P(n,t);return r<0?n.push([t,e]):n[r][1]=e,this},O.prototype.clear=function(){this.__data__={hash:new E,map:new(S||I),string:new E}},O.prototype.delete=function(t){return T(this,t).delete(t)},O.prototype.get=function(t){return T(this,t).get(t)},O.prototype.has=function(t){return T(this,t).has(t)},O.prototype.set=function(t,e){return T(this,t).set(t,e),this},x.Cache=O,t.exports=x},40117:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(91621),n(27481),n(90105),n(14718),n(80404),n(44396),n(67068),n(46977),n(13521),n(84090),n(88315),n(25766),n(53618),n(92947);var o="__lodash_hash_undefined__",i=9007199254740991,a="[object Arguments]",u="[object AsyncFunction]",c="[object Function]",s="[object GeneratorFunction]",l="[object Null]",f="[object Object]",p="[object Proxy]",d="[object Undefined]",h=/^\[object .+?Constructor\]$/,y=/^(?:0|[1-9]\d*)$/,v={};v["[object Float32Array]"]=v["[object Float64Array]"]=v["[object Int8Array]"]=v["[object Int16Array]"]=v["[object Int32Array]"]=v["[object Uint8Array]"]=v["[object Uint8ClampedArray]"]=v["[object Uint16Array]"]=v["[object Uint32Array]"]=!0,v[a]=v["[object Array]"]=v["[object ArrayBuffer]"]=v["[object Boolean]"]=v["[object DataView]"]=v["[object Date]"]=v["[object Error]"]=v[c]=v["[object Map]"]=v["[object Number]"]=v[f]=v["[object RegExp]"]=v["[object Set]"]=v["[object String]"]=v["[object WeakMap]"]=!1;var m,g,b,_="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,w="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,S=_||w||Function("return this")(),C="object"==r(e)&&e&&!e.nodeType&&e,E=C&&"object"==r(t)&&t&&!t.nodeType&&t,I=E&&E.exports===C,O=I&&_.process,P=function(){try{return E&&E.require&&E.require("util").types||O&&O.binding&&O.binding("util")}catch(t){}}(),T=P&&P.isTypedArray,A=Array.prototype,x=Function.prototype,k=Object.prototype,R=S["__core-js_shared__"],M=x.toString,j=k.hasOwnProperty,N=(m=/[^.]+$/.exec(R&&R.keys&&R.keys.IE_PROTO||""))?"Symbol(src)_1."+m:"",D=k.toString,L=M.call(Object),z=RegExp("^"+M.call(j).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=I?S.Buffer:void 0,F=S.Symbol,B=S.Uint8Array,q=(U&&U.allocUnsafe,g=Object.getPrototypeOf,b=Object,function(t){return g(b(t))}),V=Object.create,G=k.propertyIsEnumerable,H=A.splice,Y=F?F.toStringTag:void 0,W=function(){try{var t=dt(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),K=U?U.isBuffer:void 0,$=Math.max,Q=Date.now,Z=dt(S,"Map"),J=dt(Object,"create"),X=function(){function t(){}return function(e){if(!It(e))return{};if(V)return V(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();function tt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e-1},et.prototype.set=function(t,e){var n=this.__data__,r=at(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},nt.prototype.clear=function(){this.size=0,this.__data__={hash:new tt,map:new(Z||et),string:new tt}},nt.prototype.delete=function(t){var e=pt(this,t).delete(t);return this.size-=e?1:0,e},nt.prototype.get=function(t){return pt(this,t).get(t)},nt.prototype.has=function(t){return pt(this,t).has(t)},nt.prototype.set=function(t,e){var n=pt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},rt.prototype.clear=function(){this.__data__=new et,this.size=0},rt.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},rt.prototype.get=function(t){return this.__data__.get(t)},rt.prototype.has=function(t){return this.__data__.has(t)},rt.prototype.set=function(t,e){var n=this.__data__;if(n instanceof et){var r=n.__data__;if(!Z||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new nt(r)}return n.set(t,e),this.size=n.size,this};function ct(t){return null==t?void 0===t?d:l:Y&&Y in Object(t)?function(t){var e=j.call(t,Y),n=t[Y];try{t[Y]=void 0;var r=!0}catch(t){}var o=D.call(t);return r&&(e?t[Y]=n:delete t[Y]),o}(t):function(t){return D.call(t)}(t)}function st(t){return Ot(t)&&ct(t)==a}function lt(t,e,n,r,o){t!==e&&function(t,e,n){for(var r=-1,o=Object(t),i=n(t),a=i.length;a--;){var u=i[++r];if(!1===e(o[u],u,o))break}}(e,(function(i,a){if(o||(o=new rt),It(i))!function(t,e,n,r,o,i,a){var u=vt(t,n),c=vt(e,n),s=a.get(c);if(s)ot(t,n,s);else{var l,p,d,h,y,v=i?i(u,c,n+"",t,e,a):void 0,m=void 0===v;if(m){var g=_t(c),b=!g&&St(c),_=!g&&!b&&Pt(c);v=c,g||b||_?_t(u)?v=u:Ot(y=u)&&wt(y)?v=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(ft);function gt(t,e){return t===e||t!=t&&e!=e}var bt=st(function(){return arguments}())?st:function(t){return Ot(t)&&j.call(t,"callee")&&!G.call(t,"callee")},_t=Array.isArray;function wt(t){return null!=t&&Et(t.length)&&!Ct(t)}var St=K||function(){return!1};function Ct(t){if(!It(t))return!1;var e=ct(t);return e==c||e==s||e==u||e==p}function Et(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=i}function It(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function Ot(t){return null!=t&&"object"==r(t)}var Pt=T?function(t){return function(e){return t(e)}}(T):function(t){return Ot(t)&&Et(t.length)&&!!v[ct(t)]};function Tt(t){return wt(t)?function(t,e){var n=_t(t),r=!n&&bt(t),o=!n&&!r&&St(t),i=!n&&!r&&!o&&Pt(t),a=n||r||o||i,u=a?function(t,e){for(var n=-1,r=Array(t);++n1?e[o-1]:void 0,a=o>2?e[2]:void 0;for(i=At.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,n){if(!It(n))return!1;var o=r(e);return!!("number"==o?wt(n)&&ht(e,n.length):"string"==o&&e in n)&>(n[e],t)}(e[0],e[1],a)&&(i=o<3?void 0:i,o=1),t=Object(t);++n"']/g,W=RegExp(H.source),K=RegExp(Y.source),$=/<%-([\s\S]+?)%>/g,Q=/<%([\s\S]+?)%>/g,Z=/<%=([\s\S]+?)%>/g,J=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,X=/^\w*$/,tt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,et=/[\\^$.*+?()[\]{}|]/g,nt=RegExp(et.source),rt=/^\s+/,ot=/\s/,it=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,at=/\{\n\/\* \[wrapped with (.+)\] \*/,ut=/,? & /,ct=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,st=/[()=,{}\[\]\/\s]/,lt=/\\(\\)?/g,ft=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,pt=/\w*$/,dt=/^[-+]0x[0-9a-f]+$/i,ht=/^0b[01]+$/i,yt=/^\[object .+?Constructor\]$/,vt=/^0o[0-7]+$/i,mt=/^(?:0|[1-9]\d*)$/,gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,bt=/($^)/,_t=/['\n\r\u2028\u2029\\]/g,wt="\\ud800-\\udfff",St="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ct="\\u2700-\\u27bf",Et="a-z\\xdf-\\xf6\\xf8-\\xff",It="A-Z\\xc0-\\xd6\\xd8-\\xde",Ot="\\ufe0e\\ufe0f",Pt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Tt="["+wt+"]",At="["+Pt+"]",xt="["+St+"]",kt="\\d+",Rt="["+Ct+"]",Mt="["+Et+"]",jt="[^"+wt+Pt+kt+Ct+Et+It+"]",Nt="\\ud83c[\\udffb-\\udfff]",Dt="[^"+wt+"]",Lt="(?:\\ud83c[\\udde6-\\uddff]){2}",zt="[\\ud800-\\udbff][\\udc00-\\udfff]",Ut="["+It+"]",Ft="\\u200d",Bt="(?:"+Mt+"|"+jt+")",qt="(?:"+Ut+"|"+jt+")",Vt="(?:['’](?:d|ll|m|re|s|t|ve))?",Gt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ht="(?:"+xt+"|"+Nt+")?",Yt="["+Ot+"]?",Wt=Yt+Ht+"(?:"+Ft+"(?:"+[Dt,Lt,zt].join("|")+")"+Yt+Ht+")*",Kt="(?:"+[Rt,Lt,zt].join("|")+")"+Wt,$t="(?:"+[Dt+xt+"?",xt,Lt,zt,Tt].join("|")+")",Qt=RegExp("['’]","g"),Zt=RegExp(xt,"g"),Jt=RegExp(Nt+"(?="+Nt+")|"+$t+Wt,"g"),Xt=RegExp([Ut+"?"+Mt+"+"+Vt+"(?="+[At,Ut,"$"].join("|")+")",qt+"+"+Gt+"(?="+[At,Ut+Bt,"$"].join("|")+")",Ut+"?"+Bt+"+"+Vt,Ut+"+"+Gt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",kt,Kt].join("|"),"g"),te=RegExp("["+Ft+wt+St+Ot+"]"),ee=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ne=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],re=-1,oe={};oe[M]=oe[j]=oe[N]=oe[D]=oe[L]=oe[z]=oe[U]=oe[F]=oe[B]=!0,oe[y]=oe[v]=oe[k]=oe[m]=oe[R]=oe[g]=oe[b]=oe[_]=oe[S]=oe[C]=oe[E]=oe[O]=oe[P]=oe[T]=oe[x]=!1;var ie={};ie[y]=ie[v]=ie[k]=ie[R]=ie[m]=ie[g]=ie[M]=ie[j]=ie[N]=ie[D]=ie[L]=ie[S]=ie[C]=ie[E]=ie[O]=ie[P]=ie[T]=ie[A]=ie[z]=ie[U]=ie[F]=ie[B]=!0,ie[b]=ie[_]=ie[x]=!1;var ae={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ue=parseFloat,ce=parseInt,se="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,le="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,fe=se||le||Function("return this")(),pe="object"==r(e)&&e&&!e.nodeType&&e,de=pe&&"object"==r(t)&&t&&!t.nodeType&&t,he=de&&de.exports===pe,ye=he&&se.process,ve=function(){try{return de&&de.require&&de.require("util").types||ye&&ye.binding&&ye.binding("util")}catch(t){}}(),me=ve&&ve.isArrayBuffer,ge=ve&&ve.isDate,be=ve&&ve.isMap,_e=ve&&ve.isRegExp,we=ve&&ve.isSet,Se=ve&&ve.isTypedArray;function Ce(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Ee(t,e,n,r){for(var o=-1,i=null==t?0:t.length;++o-1}function xe(t,e,n){for(var r=-1,o=null==t?0:t.length;++r-1;);return n}function Xe(t,e){for(var n=t.length;n--&&Ue(e,t[n],0)>-1;);return n}var tn=Ge({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),en=Ge({"&":"&","<":"<",">":">",'"':""","'":"'"});function nn(t){return"\\"+ae[t]}function rn(t){return te.test(t)}function on(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function an(t,e){return function(n){return t(e(n))}}function un(t,e){for(var n=-1,r=t.length,o=0,i=[];++n",""":'"',"'":"'"}),hn=function t(e){var n,ot=(e=null==e?fe:hn.defaults(fe.Object(),e,hn.pick(fe,ne))).Array,wt=e.Date,St=e.Error,Ct=e.Function,Et=e.Math,It=e.Object,Ot=e.RegExp,Pt=e.String,Tt=e.TypeError,At=ot.prototype,xt=Ct.prototype,kt=It.prototype,Rt=e["__core-js_shared__"],Mt=xt.toString,jt=kt.hasOwnProperty,Nt=0,Dt=(n=/[^.]+$/.exec(Rt&&Rt.keys&&Rt.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",Lt=kt.toString,zt=Mt.call(It),Ut=fe._,Ft=Ot("^"+Mt.call(jt).replace(et,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bt=he?e.Buffer:o,qt=e.Symbol,Vt=e.Uint8Array,Gt=Bt?Bt.allocUnsafe:o,Ht=an(It.getPrototypeOf,It),Yt=It.create,Wt=kt.propertyIsEnumerable,Kt=At.splice,$t=qt?qt.isConcatSpreadable:o,Jt=qt?qt.iterator:o,te=qt?qt.toStringTag:o,ae=function(){try{var t=li(It,"defineProperty");return t({},"",{}),t}catch(t){}}(),se=e.clearTimeout!==fe.clearTimeout&&e.clearTimeout,le=wt&&wt.now!==fe.Date.now&&wt.now,pe=e.setTimeout!==fe.setTimeout&&e.setTimeout,de=Et.ceil,ye=Et.floor,ve=It.getOwnPropertySymbols,De=Bt?Bt.isBuffer:o,Ge=e.isFinite,yn=At.join,vn=an(It.keys,It),mn=Et.max,gn=Et.min,bn=wt.now,_n=e.parseInt,wn=Et.random,Sn=At.reverse,Cn=li(e,"DataView"),En=li(e,"Map"),In=li(e,"Promise"),On=li(e,"Set"),Pn=li(e,"WeakMap"),Tn=li(It,"create"),An=Pn&&new Pn,xn={},kn=zi(Cn),Rn=zi(En),Mn=zi(In),jn=zi(On),Nn=zi(Pn),Dn=qt?qt.prototype:o,Ln=Dn?Dn.valueOf:o,zn=Dn?Dn.toString:o;function Un(t){if(eu(t)&&!Ga(t)&&!(t instanceof Vn)){if(t instanceof qn)return t;if(jt.call(t,"__wrapped__"))return Ui(t)}return new qn(t)}var Fn=function(){function t(){}return function(e){if(!tu(e))return{};if(Yt)return Yt(e);t.prototype=e;var n=new t;return t.prototype=o,n}}();function Bn(){}function qn(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=o}function Vn(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=d,this.__views__=[]}function Gn(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function ur(t,e,n,r,i,a){var u,c=1&e,s=2&e,l=4&e;if(n&&(u=i?n(t,r,i,a):n(t)),u!==o)return u;if(!tu(t))return t;var f=Ga(t);if(f){if(u=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&jt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!c)return To(t,u)}else{var p=di(t),d=p==_||p==w;if(Ka(t))return So(t,c);if(p==E||p==y||d&&!i){if(u=s||d?{}:yi(t),!c)return s?function(t,e){return Ao(t,pi(t),e)}(t,function(t,e){return t&&Ao(e,Ru(e),t)}(u,t)):function(t,e){return Ao(t,fi(t),e)}(t,rr(u,t))}else{if(!ie[p])return i?t:{};u=function(t,e,n){var r,o=t.constructor;switch(e){case k:return Co(t);case m:case g:return new o(+t);case R:return function(t,e){var n=e?Co(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case M:case j:case N:case D:case L:case z:case U:case F:case B:return Eo(t,n);case S:return new o;case C:case T:return new o(t);case O:return function(t){var e=new t.constructor(t.source,pt.exec(t));return e.lastIndex=t.lastIndex,e}(t);case P:return new o;case A:return r=t,Ln?It(Ln.call(r)):{}}}(t,p,c)}}a||(a=new Kn);var h=a.get(t);if(h)return h;a.set(t,u),au(t)?t.forEach((function(r){u.add(ur(r,e,n,r,t,a))})):nu(t)&&t.forEach((function(r,o){u.set(o,ur(r,e,n,o,t,a))}));var v=f?o:(l?s?ri:ni:s?Ru:ku)(t);return Ie(v||t,(function(r,o){v&&(r=t[o=r]),tr(u,o,ur(r,e,n,o,t,a))})),u}function cr(t,e,n){var r=n.length;if(null==t)return!r;for(t=It(t);r--;){var i=n[r],a=e[i],u=t[i];if(u===o&&!(i in t)||!a(u))return!1}return!0}function sr(t,e,n){if("function"!=typeof t)throw new Tt(i);return Ai((function(){t.apply(o,n)}),e)}function lr(t,e,n,r){var o=-1,i=Ae,a=!0,u=t.length,c=[],s=e.length;if(!u)return c;n&&(e=ke(e,$e(n))),r?(i=xe,a=!1):e.length>=200&&(i=Ze,a=!1,e=new Wn(e));t:for(;++o-1},Hn.prototype.set=function(t,e){var n=this.__data__,r=er(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},Yn.prototype.clear=function(){this.size=0,this.__data__={hash:new Gn,map:new(En||Hn),string:new Gn}},Yn.prototype.delete=function(t){var e=ci(this,t).delete(t);return this.size-=e?1:0,e},Yn.prototype.get=function(t){return ci(this,t).get(t)},Yn.prototype.has=function(t){return ci(this,t).has(t)},Yn.prototype.set=function(t,e){var n=ci(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},Wn.prototype.add=Wn.prototype.push=function(t){return this.__data__.set(t,a),this},Wn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.clear=function(){this.__data__=new Hn,this.size=0},Kn.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},Kn.prototype.get=function(t){return this.__data__.get(t)},Kn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Hn){var r=n.__data__;if(!En||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Yn(r)}return n.set(t,e),this.size=n.size,this};var fr=Ro(br),pr=Ro(_r,!0);function dr(t,e){var n=!0;return fr(t,(function(t,r,o){return n=!!e(t,r,o)})),n}function hr(t,e,n){for(var r=-1,i=t.length;++r0&&n(u)?e>1?vr(u,e-1,n,r,o):Re(o,u):r||(o[o.length]=u)}return o}var mr=Mo(),gr=Mo(!0);function br(t,e){return t&&mr(t,e,ku)}function _r(t,e){return t&&gr(t,e,ku)}function wr(t,e){return Te(e,(function(e){return Za(t[e])}))}function Sr(t,e){for(var n=0,r=(e=go(e,t)).length;null!=t&&ne}function Or(t,e){return null!=t&&jt.call(t,e)}function Pr(t,e){return null!=t&&e in It(t)}function Tr(t,e,n){for(var r=n?xe:Ae,i=t[0].length,a=t.length,u=a,c=ot(a),s=1/0,l=[];u--;){var f=t[u];u&&e&&(f=ke(f,$e(e))),s=gn(f.length,s),c[u]=!n&&(e||i>=120&&f.length>=120)?new Wn(u&&f):o}f=t[0];var p=-1,d=c[0];t:for(;++p=u?c:c*("desc"==n[r]?-1:1)}return t.index-e.index}(t,e,n)}));e--;)t[e]=t[e].value;return t}(o)}function Vr(t,e,n){for(var r=-1,o=e.length,i={};++r-1;)u!==t&&Kt.call(u,c,1),Kt.call(t,c,1);return t}function Hr(t,e){for(var n=t?e.length:0,r=n-1;n--;){var o=e[n];if(n==r||o!==i){var i=o;mi(o)?Kt.call(t,o,1):so(t,o)}}return t}function Yr(t,e){return t+ye(wn()*(e-t+1))}function Wr(t,e){var n="";if(!t||e<1||e>f)return n;do{e%2&&(n+=t),(e=ye(e/2))&&(t+=t)}while(e);return n}function Kr(t,e){return xi(Ii(t,e,rc),t+"")}function $r(t){return Qn(Fu(t))}function Qr(t,e){var n=Fu(t);return Mi(n,ar(e,0,n.length))}function Zr(t,e,n,r){if(!tu(t))return t;for(var i=-1,a=(e=go(e,t)).length,u=a-1,c=t;null!=c&&++io?0:o+e),(n=n>o?o:n)<0&&(n+=o),o=e>n?0:n-e>>>0,e>>>=0;for(var i=ot(o);++r>>1,a=t[i];null!==a&&!cu(a)&&(n?a<=e:a=200){var s=e?null:Ko(t);if(s)return cn(s);a=!1,o=Ze,c=new Wn}else c=e?[]:u;t:for(;++r=r?t:eo(t,e,n)}var wo=se||function(t){return fe.clearTimeout(t)};function So(t,e){if(e)return t.slice();var n=t.length,r=Gt?Gt(n):new t.constructor(n);return t.copy(r),r}function Co(t){var e=new t.constructor(t.byteLength);return new Vt(e).set(new Vt(t)),e}function Eo(t,e){var n=e?Co(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Io(t,e){if(t!==e){var n=t!==o,r=null===t,i=t==t,a=cu(t),u=e!==o,c=null===e,s=e==e,l=cu(e);if(!c&&!l&&!a&&t>e||a&&u&&s&&!c&&!l||r&&u&&s||!n&&s||!i)return 1;if(!r&&!a&&!l&&t1?n[i-1]:o,u=i>2?n[2]:o;for(a=t.length>3&&"function"==typeof a?(i--,a):o,u&&gi(n[0],n[1],u)&&(a=i<3?o:a,i=1),e=It(e);++r-1?i[a?e[u]:u]:o}}function zo(t){return ei((function(e){var n=e.length,r=n,a=qn.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new Tt(i);if(a&&!c&&"wrapper"==ii(u))var c=new qn([],!0)}for(r=c?r:n;++r1&&b.reverse(),p&&lc))return!1;var l=a.get(t),f=a.get(e);if(l&&f)return l==e&&f==t;var p=-1,d=!0,h=2&n?new Wn:o;for(a.set(t,e),a.set(e,t);++p-1&&t%1==0&&t1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(it,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return Ie(h,(function(n){var r="_."+n[0];e&n[1]&&!Ae(t,r)&&t.push(r)})),t.sort()}(function(t){var e=t.match(at);return e?e[1].split(ut):[]}(r),n)))}function Ri(t){var e=0,n=0;return function(){var r=bn(),i=16-(r-n);if(n=r,i>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(o,arguments)}}function Mi(t,e){var n=-1,r=t.length,i=r-1;for(e=e===o?r:e;++n1?t[e-1]:o;return n="function"==typeof n?(t.pop(),n):o,ia(t,n)}));function pa(t){var e=Un(t);return e.__chain__=!0,e}function da(t,e){return e(t)}var ha=ei((function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,i=function(e){return ir(e,t)};return!(e>1||this.__actions__.length)&&r instanceof Vn&&mi(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:da,args:[i],thisArg:o}),new qn(r,this.__chain__).thru((function(t){return e&&!t.length&&t.push(o),t}))):this.thru(i)})),ya=xo((function(t,e,n){jt.call(t,n)?++t[n]:or(t,n,1)})),va=Lo(Vi),ma=Lo(Gi);function ga(t,e){return(Ga(t)?Ie:fr)(t,ui(e,3))}function ba(t,e){return(Ga(t)?Oe:pr)(t,ui(e,3))}var _a=xo((function(t,e,n){jt.call(t,n)?t[n].push(e):or(t,n,[e])})),wa=Kr((function(t,e,n){var r=-1,o="function"==typeof e,i=Ya(t)?ot(t.length):[];return fr(t,(function(t){i[++r]=o?Ce(e,t,n):Ar(t,e,n)})),i})),Sa=xo((function(t,e,n){or(t,n,e)}));function Ca(t,e){return(Ga(t)?ke:Lr)(t,ui(e,3))}var Ea=xo((function(t,e,n){t[n?0:1].push(e)}),(function(){return[[],[]]})),Ia=Kr((function(t,e){if(null==t)return[];var n=e.length;return n>1&&gi(t,e[0],e[1])?e=[]:n>2&&gi(e[0],e[1],e[2])&&(e=[e[0]]),qr(t,vr(e,1),[])})),Oa=le||function(){return fe.Date.now()};function Pa(t,e,n){return e=n?o:e,e=t&&null==e?t.length:e,Qo(t,s,o,o,o,o,e)}function Ta(t,e){var n;if("function"!=typeof e)throw new Tt(i);return t=hu(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=o),n}}var Aa=Kr((function(t,e,n){var r=1;if(n.length){var o=un(n,ai(Aa));r|=c}return Qo(t,r,e,n,o)})),xa=Kr((function(t,e,n){var r=3;if(n.length){var o=un(n,ai(xa));r|=c}return Qo(e,r,t,n,o)}));function ka(t,e,n){var r,a,u,c,s,l,f=0,p=!1,d=!1,h=!0;if("function"!=typeof t)throw new Tt(i);function y(e){var n=r,i=a;return r=a=o,f=e,c=t.apply(i,n)}function v(t){var n=t-l;return l===o||n>=e||n<0||d&&t-f>=u}function m(){var t=Oa();if(v(t))return g(t);s=Ai(m,function(t){var n=e-(t-l);return d?gn(n,u-(t-f)):n}(t))}function g(t){return s=o,h&&r?y(t):(r=a=o,c)}function b(){var t=Oa(),n=v(t);if(r=arguments,a=this,l=t,n){if(s===o)return function(t){return f=t,s=Ai(m,e),p?y(t):c}(l);if(d)return wo(s),s=Ai(m,e),y(l)}return s===o&&(s=Ai(m,e)),c}return e=vu(e)||0,tu(n)&&(p=!!n.leading,u=(d="maxWait"in n)?mn(vu(n.maxWait)||0,e):u,h="trailing"in n?!!n.trailing:h),b.cancel=function(){s!==o&&wo(s),f=0,r=l=a=s=o},b.flush=function(){return s===o?c:g(Oa())},b}var Ra=Kr((function(t,e){return sr(t,1,e)})),Ma=Kr((function(t,e,n){return sr(t,vu(e)||0,n)}));function ja(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new Tt(i);var n=function n(){var r=arguments,o=e?e.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=t.apply(this,r);return n.cache=i.set(o,a)||i,a};return n.cache=new(ja.Cache||Yn),n}function Na(t){if("function"!=typeof t)throw new Tt(i);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}ja.Cache=Yn;var Da=bo((function(t,e){var n=(e=1==e.length&&Ga(e[0])?ke(e[0],$e(ui())):ke(vr(e,1),$e(ui()))).length;return Kr((function(r){for(var o=-1,i=gn(r.length,n);++o=e})),Va=xr(function(){return arguments}())?xr:function(t){return eu(t)&&jt.call(t,"callee")&&!Wt.call(t,"callee")},Ga=ot.isArray,Ha=me?$e(me):function(t){return eu(t)&&Er(t)==k};function Ya(t){return null!=t&&Xa(t.length)&&!Za(t)}function Wa(t){return eu(t)&&Ya(t)}var Ka=De||vc,$a=ge?$e(ge):function(t){return eu(t)&&Er(t)==g};function Qa(t){if(!eu(t))return!1;var e=Er(t);return e==b||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!ou(t)}function Za(t){if(!tu(t))return!1;var e=Er(t);return e==_||e==w||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Ja(t){return"number"==typeof t&&t==hu(t)}function Xa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=f}function tu(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function eu(t){return null!=t&&"object"==r(t)}var nu=be?$e(be):function(t){return eu(t)&&di(t)==S};function ru(t){return"number"==typeof t||eu(t)&&Er(t)==C}function ou(t){if(!eu(t)||Er(t)!=E)return!1;var e=Ht(t);if(null===e)return!0;var n=jt.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&Mt.call(n)==zt}var iu=_e?$e(_e):function(t){return eu(t)&&Er(t)==O},au=we?$e(we):function(t){return eu(t)&&di(t)==P};function uu(t){return"string"==typeof t||!Ga(t)&&eu(t)&&Er(t)==T}function cu(t){return"symbol"==r(t)||eu(t)&&Er(t)==A}var su=Se?$e(Se):function(t){return eu(t)&&Xa(t.length)&&!!oe[Er(t)]},lu=Ho(Dr),fu=Ho((function(t,e){return t<=e}));function pu(t){if(!t)return[];if(Ya(t))return uu(t)?fn(t):To(t);if(Jt&&t[Jt])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[Jt]());var e=di(t);return(e==S?on:e==P?cn:Fu)(t)}function du(t){return t?(t=vu(t))===l||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function hu(t){var e=du(t),n=e%1;return e==e?n?e-n:e:0}function yu(t){return t?ar(hu(t),0,d):0}function vu(t){if("number"==typeof t)return t;if(cu(t))return p;if(tu(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=tu(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Ke(t);var n=ht.test(t);return n||vt.test(t)?ce(t.slice(2),n?2:8):dt.test(t)?p:+t}function mu(t){return Ao(t,Ru(t))}function gu(t){return null==t?"":uo(t)}var bu=ko((function(t,e){if(Si(e)||Ya(e))Ao(e,ku(e),t);else for(var n in e)jt.call(e,n)&&tr(t,n,e[n])})),_u=ko((function(t,e){Ao(e,Ru(e),t)})),wu=ko((function(t,e,n,r){Ao(e,Ru(e),t,r)})),Su=ko((function(t,e,n,r){Ao(e,ku(e),t,r)})),Cu=ei(ir),Eu=Kr((function(t,e){t=It(t);var n=-1,r=e.length,i=r>2?e[2]:o;for(i&&gi(e[0],e[1],i)&&(r=1);++n1),e})),Ao(t,ri(t),n),r&&(n=ur(n,7,Xo));for(var o=e.length;o--;)so(n,e[o]);return n})),Du=ei((function(t,e){return null==t?{}:function(t,e){return Vr(t,e,(function(e,n){return Pu(t,n)}))}(t,e)}));function Lu(t,e){if(null==t)return{};var n=ke(ri(t),(function(t){return[t]}));return e=ui(e),Vr(t,n,(function(t,n){return e(t,n[0])}))}var zu=$o(ku),Uu=$o(Ru);function Fu(t){return null==t?[]:Qe(t,ku(t))}var Bu=No((function(t,e,n){return e=e.toLowerCase(),t+(n?qu(e):e)}));function qu(t){return Qu(gu(t).toLowerCase())}function Vu(t){return(t=gu(t))&&t.replace(gt,tn).replace(Zt,"")}var Gu=No((function(t,e,n){return t+(n?"-":"")+e.toLowerCase()})),Hu=No((function(t,e,n){return t+(n?" ":"")+e.toLowerCase()})),Yu=jo("toLowerCase"),Wu=No((function(t,e,n){return t+(n?"_":"")+e.toLowerCase()})),Ku=No((function(t,e,n){return t+(n?" ":"")+Qu(e)})),$u=No((function(t,e,n){return t+(n?" ":"")+e.toUpperCase()})),Qu=jo("toUpperCase");function Zu(t,e,n){return t=gu(t),(e=n?o:e)===o?function(t){return ee.test(t)}(t)?function(t){return t.match(Xt)||[]}(t):function(t){return t.match(ct)||[]}(t):t.match(e)||[]}var Ju=Kr((function(t,e){try{return Ce(t,o,e)}catch(t){return Qa(t)?t:new St(t)}})),Xu=ei((function(t,e){return Ie(e,(function(e){e=Li(e),or(t,e,Aa(t[e],t))})),t}));function tc(t){return function(){return t}}var ec=zo(),nc=zo(!0);function rc(t){return t}function oc(t){return jr("function"==typeof t?t:ur(t,1))}var ic=Kr((function(t,e){return function(n){return Ar(n,t,e)}})),ac=Kr((function(t,e){return function(n){return Ar(t,n,e)}}));function uc(t,e,n){var r=ku(e),o=wr(e,r);null!=n||tu(e)&&(o.length||!r.length)||(n=e,e=t,t=this,o=wr(e,ku(e)));var i=!(tu(n)&&"chain"in n&&!n.chain),a=Za(t);return Ie(o,(function(n){var r=e[n];t[n]=r,a&&(t.prototype[n]=function(){var e=this.__chain__;if(i||e){var n=t(this.__wrapped__);return(n.__actions__=To(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,Re([this.value()],arguments))})})),t}function cc(){}var sc=qo(ke),lc=qo(Pe),fc=qo(Ne);function pc(t){return bi(t)?Ve(Li(t)):function(t){return function(e){return Sr(e,t)}}(t)}var dc=Go(),hc=Go(!0);function yc(){return[]}function vc(){return!1}var mc,gc=Bo((function(t,e){return t+e}),0),bc=Wo("ceil"),_c=Bo((function(t,e){return t/e}),1),wc=Wo("floor"),Sc=Bo((function(t,e){return t*e}),1),Cc=Wo("round"),Ec=Bo((function(t,e){return t-e}),0);return Un.after=function(t,e){if("function"!=typeof e)throw new Tt(i);return t=hu(t),function(){if(--t<1)return e.apply(this,arguments)}},Un.ary=Pa,Un.assign=bu,Un.assignIn=_u,Un.assignInWith=wu,Un.assignWith=Su,Un.at=Cu,Un.before=Ta,Un.bind=Aa,Un.bindAll=Xu,Un.bindKey=xa,Un.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Ga(t)?t:[t]},Un.chain=pa,Un.chunk=function(t,e,n){e=(n?gi(t,e,n):e===o)?1:mn(hu(e),0);var r=null==t?0:t.length;if(!r||e<1)return[];for(var i=0,a=0,u=ot(de(r/e));ii?0:i+n),(r=r===o||r>i?i:hu(r))<0&&(r+=i),r=n>r?0:yu(r);n>>0)?(t=gu(t))&&("string"==typeof e||null!=e&&!iu(e))&&!(e=uo(e))&&rn(t)?_o(fn(t),0,n):t.split(e,n):[]},Un.spread=function(t,e){if("function"!=typeof t)throw new Tt(i);return e=null==e?0:mn(hu(e),0),Kr((function(n){var r=n[e],o=_o(n,0,e);return r&&Re(o,r),Ce(t,this,o)}))},Un.tail=function(t){var e=null==t?0:t.length;return e?eo(t,1,e):[]},Un.take=function(t,e,n){return t&&t.length?eo(t,0,(e=n||e===o?1:hu(e))<0?0:e):[]},Un.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?eo(t,(e=r-(e=n||e===o?1:hu(e)))<0?0:e,r):[]},Un.takeRightWhile=function(t,e){return t&&t.length?fo(t,ui(e,3),!1,!0):[]},Un.takeWhile=function(t,e){return t&&t.length?fo(t,ui(e,3)):[]},Un.tap=function(t,e){return e(t),t},Un.throttle=function(t,e,n){var r=!0,o=!0;if("function"!=typeof t)throw new Tt(i);return tu(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),ka(t,e,{leading:r,maxWait:e,trailing:o})},Un.thru=da,Un.toArray=pu,Un.toPairs=zu,Un.toPairsIn=Uu,Un.toPath=function(t){return Ga(t)?ke(t,Li):cu(t)?[t]:To(Di(gu(t)))},Un.toPlainObject=mu,Un.transform=function(t,e,n){var r=Ga(t),o=r||Ka(t)||su(t);if(e=ui(e,4),null==n){var i=t&&t.constructor;n=o?r?new i:[]:tu(t)&&Za(i)?Fn(Ht(t)):{}}return(o?Ie:br)(t,(function(t,r,o){return e(n,t,r,o)})),n},Un.unary=function(t){return Pa(t,1)},Un.union=ea,Un.unionBy=na,Un.unionWith=ra,Un.uniq=function(t){return t&&t.length?co(t):[]},Un.uniqBy=function(t,e){return t&&t.length?co(t,ui(e,2)):[]},Un.uniqWith=function(t,e){return e="function"==typeof e?e:o,t&&t.length?co(t,o,e):[]},Un.unset=function(t,e){return null==t||so(t,e)},Un.unzip=oa,Un.unzipWith=ia,Un.update=function(t,e,n){return null==t?t:lo(t,e,mo(n))},Un.updateWith=function(t,e,n,r){return r="function"==typeof r?r:o,null==t?t:lo(t,e,mo(n),r)},Un.values=Fu,Un.valuesIn=function(t){return null==t?[]:Qe(t,Ru(t))},Un.without=aa,Un.words=Zu,Un.wrap=function(t,e){return La(mo(e),t)},Un.xor=ua,Un.xorBy=ca,Un.xorWith=sa,Un.zip=la,Un.zipObject=function(t,e){return yo(t||[],e||[],tr)},Un.zipObjectDeep=function(t,e){return yo(t||[],e||[],Zr)},Un.zipWith=fa,Un.entries=zu,Un.entriesIn=Uu,Un.extend=_u,Un.extendWith=wu,uc(Un,Un),Un.add=gc,Un.attempt=Ju,Un.camelCase=Bu,Un.capitalize=qu,Un.ceil=bc,Un.clamp=function(t,e,n){return n===o&&(n=e,e=o),n!==o&&(n=(n=vu(n))==n?n:0),e!==o&&(e=(e=vu(e))==e?e:0),ar(vu(t),e,n)},Un.clone=function(t){return ur(t,4)},Un.cloneDeep=function(t){return ur(t,5)},Un.cloneDeepWith=function(t,e){return ur(t,5,e="function"==typeof e?e:o)},Un.cloneWith=function(t,e){return ur(t,4,e="function"==typeof e?e:o)},Un.conformsTo=function(t,e){return null==e||cr(t,e,ku(e))},Un.deburr=Vu,Un.defaultTo=function(t,e){return null==t||t!=t?e:t},Un.divide=_c,Un.endsWith=function(t,e,n){t=gu(t),e=uo(e);var r=t.length,i=n=n===o?r:ar(hu(n),0,r);return(n-=e.length)>=0&&t.slice(n,i)==e},Un.eq=Fa,Un.escape=function(t){return(t=gu(t))&&K.test(t)?t.replace(Y,en):t},Un.escapeRegExp=function(t){return(t=gu(t))&&nt.test(t)?t.replace(et,"\\$&"):t},Un.every=function(t,e,n){var r=Ga(t)?Pe:dr;return n&&gi(t,e,n)&&(e=o),r(t,ui(e,3))},Un.find=va,Un.findIndex=Vi,Un.findKey=function(t,e){return Le(t,ui(e,3),br)},Un.findLast=ma,Un.findLastIndex=Gi,Un.findLastKey=function(t,e){return Le(t,ui(e,3),_r)},Un.floor=wc,Un.forEach=ga,Un.forEachRight=ba,Un.forIn=function(t,e){return null==t?t:mr(t,ui(e,3),Ru)},Un.forInRight=function(t,e){return null==t?t:gr(t,ui(e,3),Ru)},Un.forOwn=function(t,e){return t&&br(t,ui(e,3))},Un.forOwnRight=function(t,e){return t&&_r(t,ui(e,3))},Un.get=Ou,Un.gt=Ba,Un.gte=qa,Un.has=function(t,e){return null!=t&&hi(t,e,Or)},Un.hasIn=Pu,Un.head=Yi,Un.identity=rc,Un.includes=function(t,e,n,r){t=Ya(t)?t:Fu(t),n=n&&!r?hu(n):0;var o=t.length;return n<0&&(n=mn(o+n,0)),uu(t)?n<=o&&t.indexOf(e,n)>-1:!!o&&Ue(t,e,n)>-1},Un.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=null==n?0:hu(n);return o<0&&(o=mn(r+o,0)),Ue(t,e,o)},Un.inRange=function(t,e,n){return e=du(e),n===o?(n=e,e=0):n=du(n),function(t,e,n){return t>=gn(e,n)&&t=-9007199254740991&&t<=f},Un.isSet=au,Un.isString=uu,Un.isSymbol=cu,Un.isTypedArray=su,Un.isUndefined=function(t){return t===o},Un.isWeakMap=function(t){return eu(t)&&di(t)==x},Un.isWeakSet=function(t){return eu(t)&&"[object WeakSet]"==Er(t)},Un.join=function(t,e){return null==t?"":yn.call(t,e)},Un.kebabCase=Gu,Un.last=Qi,Un.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r;return n!==o&&(i=(i=hu(n))<0?mn(r+i,0):gn(i,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,i):ze(t,Be,i,!0)},Un.lowerCase=Hu,Un.lowerFirst=Yu,Un.lt=lu,Un.lte=fu,Un.max=function(t){return t&&t.length?hr(t,rc,Ir):o},Un.maxBy=function(t,e){return t&&t.length?hr(t,ui(e,2),Ir):o},Un.mean=function(t){return qe(t,rc)},Un.meanBy=function(t,e){return qe(t,ui(e,2))},Un.min=function(t){return t&&t.length?hr(t,rc,Dr):o},Un.minBy=function(t,e){return t&&t.length?hr(t,ui(e,2),Dr):o},Un.stubArray=yc,Un.stubFalse=vc,Un.stubObject=function(){return{}},Un.stubString=function(){return""},Un.stubTrue=function(){return!0},Un.multiply=Sc,Un.nth=function(t,e){return t&&t.length?Br(t,hu(e)):o},Un.noConflict=function(){return fe._===this&&(fe._=Ut),this},Un.noop=cc,Un.now=Oa,Un.pad=function(t,e,n){t=gu(t);var r=(e=hu(e))?ln(t):0;if(!e||r>=e)return t;var o=(e-r)/2;return Vo(ye(o),n)+t+Vo(de(o),n)},Un.padEnd=function(t,e,n){t=gu(t);var r=(e=hu(e))?ln(t):0;return e&&re){var r=t;t=e,e=r}if(n||t%1||e%1){var i=wn();return gn(t+i*(e-t+ue("1e-"+((i+"").length-1))),e)}return Yr(t,e)},Un.reduce=function(t,e,n){var r=Ga(t)?Me:He,o=arguments.length<3;return r(t,ui(e,4),n,o,fr)},Un.reduceRight=function(t,e,n){var r=Ga(t)?je:He,o=arguments.length<3;return r(t,ui(e,4),n,o,pr)},Un.repeat=function(t,e,n){return e=(n?gi(t,e,n):e===o)?1:hu(e),Wr(gu(t),e)},Un.replace=function(){var t=arguments,e=gu(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Un.result=function(t,e,n){var r=-1,i=(e=go(e,t)).length;for(i||(i=1,t=o);++rf)return[];var n=d,r=gn(t,d);e=ui(e),t-=d;for(var o=We(r,e);++n=a)return t;var c=n-ln(r);if(c<1)return r;var s=u?_o(u,0,c).join(""):t.slice(0,c);if(i===o)return s+r;if(u&&(c+=s.length-c),iu(i)){if(t.slice(c).search(i)){var l,f=s;for(i.global||(i=Ot(i.source,gu(pt.exec(i))+"g")),i.lastIndex=0;l=i.exec(f);)var p=l.index;s=s.slice(0,p===o?c:p)}}else if(t.indexOf(uo(i),c)!=c){var d=s.lastIndexOf(i);d>-1&&(s=s.slice(0,d))}return s+r},Un.unescape=function(t){return(t=gu(t))&&W.test(t)?t.replace(H,dn):t},Un.uniqueId=function(t){var e=++Nt;return gu(t)+e},Un.upperCase=$u,Un.upperFirst=Qu,Un.each=ga,Un.eachRight=ba,Un.first=Yi,uc(Un,(mc={},br(Un,(function(t,e){jt.call(Un.prototype,e)||(mc[e]=t)})),mc),{chain:!1}),Un.VERSION="4.17.21",Ie(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Un[t].placeholder=Un})),Ie(["drop","take"],(function(t,e){Vn.prototype[t]=function(n){n=n===o?1:mn(hu(n),0);var r=this.__filtered__&&!e?new Vn(this):this.clone();return r.__filtered__?r.__takeCount__=gn(n,r.__takeCount__):r.__views__.push({size:gn(n,d),type:t+(r.__dir__<0?"Right":"")}),r},Vn.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}})),Ie(["filter","map","takeWhile"],(function(t,e){var n=e+1,r=1==n||3==n;Vn.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:ui(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}})),Ie(["head","last"],(function(t,e){var n="take"+(e?"Right":"");Vn.prototype[t]=function(){return this[n](1).value()[0]}})),Ie(["initial","tail"],(function(t,e){var n="drop"+(e?"":"Right");Vn.prototype[t]=function(){return this.__filtered__?new Vn(this):this[n](1)}})),Vn.prototype.compact=function(){return this.filter(rc)},Vn.prototype.find=function(t){return this.filter(t).head()},Vn.prototype.findLast=function(t){return this.reverse().find(t)},Vn.prototype.invokeMap=Kr((function(t,e){return"function"==typeof t?new Vn(this):this.map((function(n){return Ar(n,t,e)}))})),Vn.prototype.reject=function(t){return this.filter(Na(ui(t)))},Vn.prototype.slice=function(t,e){t=hu(t);var n=this;return n.__filtered__&&(t>0||e<0)?new Vn(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==o&&(n=(e=hu(e))<0?n.dropRight(-e):n.take(e-t)),n)},Vn.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Vn.prototype.toArray=function(){return this.take(d)},br(Vn.prototype,(function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),i=Un[r?"take"+("last"==e?"Right":""):e],a=r||/^find/.test(e);i&&(Un.prototype[e]=function(){var e=this.__wrapped__,u=r?[1]:arguments,c=e instanceof Vn,s=u[0],l=c||Ga(e),f=function(t){var e=i.apply(Un,Re([t],u));return r&&p?e[0]:e};l&&n&&"function"==typeof s&&1!=s.length&&(c=l=!1);var p=this.__chain__,d=!!this.__actions__.length,h=a&&!p,y=c&&!d;if(!a&&l){e=y?e:new Vn(this);var v=t.apply(e,u);return v.__actions__.push({func:da,args:[f],thisArg:o}),new qn(v,p)}return h&&y?t.apply(this,u):(v=this.thru(f),h?r?v.value()[0]:v.value():v)})})),Ie(["pop","push","shift","sort","splice","unshift"],(function(t){var e=At[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);Un.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var o=this.value();return e.apply(Ga(o)?o:[],t)}return this[n]((function(n){return e.apply(Ga(n)?n:[],t)}))}})),br(Vn.prototype,(function(t,e){var n=Un[e];if(n){var r=n.name+"";jt.call(xn,r)||(xn[r]=[]),xn[r].push({name:e,func:n})}})),xn[Uo(o,2).name]=[{name:"wrapper",func:o}],Vn.prototype.clone=function(){var t=new Vn(this.__wrapped__);return t.__actions__=To(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=To(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=To(this.__views__),t},Vn.prototype.reverse=function(){if(this.__filtered__){var t=new Vn(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},Vn.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=Ga(t),r=e<0,o=n?t.length:0,i=function(t,e,n){for(var r=-1,o=n.length;++r=this.__values__.length;return{done:t,value:t?o:this.__values__[this.__index__++]}},Un.prototype.plant=function(t){for(var e,n=this;n instanceof Bn;){var r=Ui(n);r.__index__=0,r.__values__=o,e?i.__wrapped__=r:e=r;var i=r;n=n.__wrapped__}return i.__wrapped__=t,e},Un.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Vn){var e=t;return this.__actions__.length&&(e=new Vn(this)),(e=e.reverse()).__actions__.push({func:da,args:[ta],thisArg:o}),new qn(e,this.__chain__)}return this.thru(ta)},Un.prototype.toJSON=Un.prototype.valueOf=Un.prototype.value=function(){return po(this.__wrapped__,this.__actions__)},Un.prototype.first=Un.prototype.head,Jt&&(Un.prototype[Jt]=function(){return this}),Un}();"function"==typeof define&&"object"==r(define.amd)&&define.amd?(fe._=hn,define((function(){return hn}))):de?((de.exports=hn)._=hn,pe._=hn):fe._=hn}.call(this)},95757:(t,e,n)=>{"use strict";n(91621),n(57188),n(80404),n(90291),n(32194),n(21894),n(11062);var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map((function(t){return e[t]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(t){r[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,a,u=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),c=1;c{"use strict";function r(t,e,n){return(e=function(t){var e=function(t){if("object"!==i(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!==i(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===i(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,s=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){s=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(s)throw o}}return u}}(t,e)||u(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function a(t){return function(t){if(Array.isArray(t))return c(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return c(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(t,e):void 0}}function c(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0})).join("&")},e.parseUrl=function(t,e){e=Object.assign({decode:!0},e);var n=o(f(t,"#"),2),r=n[0],i=n[1];return Object.assign({url:r.split("?")[0]||"",query:w(b(t),e)},e&&e.parseFragmentIdentifier&&i?{fragmentIdentifier:v(i,e)}:{})},e.stringifyUrl=function(t,n){n=Object.assign(r({encode:!0,strict:!0},d,!0),n);var o=g(t.url).split("?")[0]||"",i=e.extract(t.url),a=e.parse(i,{sort:!1}),u=Object.assign(a,t.query),c=e.stringify(u,n);c&&(c="?".concat(c));var s=function(t){var e="",n=t.indexOf("#");return-1!==n&&(e=t.slice(n)),e}(t.url);return t.fragmentIdentifier&&(s="#".concat(n[d]?y(t.fragmentIdentifier,n):t.fragmentIdentifier)),"".concat(o).concat(c).concat(s)},e.pick=function(t,n,o){o=Object.assign(r({parseFragmentIdentifier:!0},d,!1),o);var i=e.parseUrl(t,o),a=i.url,u=i.query,c=i.fragmentIdentifier;return e.stringifyUrl({url:a,query:p(u,n),fragmentIdentifier:c},o)},e.exclude=function(t,n,r){var o=Array.isArray(n)?function(t){return!n.includes(t)}:function(t,e){return!n(t,e)};return e.pick(t,o,r)}},73715:(t,e,n)=>{"use strict";n(13521),n(88315),n(53618),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%".concat(t.charCodeAt(0).toString(16).toUpperCase())}))}},87218:(t,e,n)=>{"use strict";n.r(e),n.d(e,{ArgumentOutOfRangeError:()=>x.k,AsyncSubject:()=>l.h,BehaviorSubject:()=>c.t,ConnectableObservable:()=>o.G,EMPTY:()=>$.w,EmptyError:()=>k.G,GroupedObservable:()=>i.k,NEVER:()=>lt,Notification:()=>I.E,NotificationKind:()=>I.I,ObjectUnsubscribedError:()=>R.P,Observable:()=>r.c,ReplaySubject:()=>s.m,Scheduler:()=>S._,Subject:()=>u.B7,Subscriber:()=>E.v,Subscription:()=>C.y,TimeoutError:()=>j.M,UnsubscriptionError:()=>M.Z,VirtualAction:()=>w,VirtualTimeScheduler:()=>_,animationFrame:()=>b,animationFrameScheduler:()=>g,asap:()=>f.I,asapScheduler:()=>f.$,async:()=>p.b,asyncScheduler:()=>p.E,bindCallback:()=>U,bindNodeCallback:()=>q,combineLatest:()=>Y.zV,concat:()=>W.x,config:()=>Tt.$,defer:()=>K.v,empty:()=>$.I,forkJoin:()=>J,from:()=>Z.H,fromEvent:()=>tt.R,fromEventPattern:()=>nt,generate:()=>rt,identity:()=>T.D,iif:()=>it,interval:()=>ut,isObservable:()=>A,merge:()=>st.h,never:()=>ft,noop:()=>P.l,observable:()=>a.s,of:()=>pt.of,onErrorResumeNext:()=>dt,pairs:()=>ht,partition:()=>bt,pipe:()=>O.F,queue:()=>d.g,queueScheduler:()=>d.T,race:()=>_t.O4,range:()=>wt,scheduled:()=>Pt.c,throwError:()=>Ct.$,timer:()=>Et.O,using:()=>It,zip:()=>Ot.yU});var r=n(97188),o=n(64952),i=n(40457),a=n(19241),u=n(47029),c=n(27399),s=n(39384),l=n(51073),f=n(35947),p=n(58687),d=n(22310),h=n(44693),y=n(12059),v=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return h.C6(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=requestAnimationFrame((function(){return e.flush(null)}))))},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(cancelAnimationFrame(n),e.scheduled=void 0)},e}(y.R),m=n(75998),g=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return h.C6(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,o=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++re.index?1:-1:t.delay>e.delay?1:-1},e}(y.R),S=n(90480),C=n(64264),E=n(72687),I=n(59038),O=n(7336),P=n(3784),T=n(63242);function A(t){return!!t&&(t instanceof r.c||"function"==typeof t.lift&&"function"==typeof t.subscribe)}var x=n(27943),k=n(88509),R=n(73404),M=n(55758),j=n(54467),N=(n(98556),n(20385)),D=n(96474),L=n(17815),z=n(11599);function U(t,e,n){if(e){if(!(0,z.m)(e))return function(){for(var r=[],o=0;o=e){r.complete();break}if(r.next(i++),r.closed)break}}))}function St(t){var e=t.start,n=t.index,r=t.count,o=t.subscriber;n>=r?o.complete():(o.next(e),o.closed||(t.index=n+1,t.start=e+1,this.schedule(t)))}var Ct=n(93033),Et=n(40930);function It(t,e){return new r.c((function(n){var r,o;try{r=t()}catch(t){return void n.error(t)}try{o=e(r)}catch(t){return void n.error(t)}var i=(o?(0,Z.H)(o):$.w).subscribe(n);return function(){i.unsubscribe(),r&&r.unsubscribe()}}))}var Ot=n(28124),Pt=n(64902),Tt=n(47255)},51073:(t,e,n)=>{"use strict";n.d(e,{h:()=>a});var r=n(44693),o=n(47029),i=n(64264),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.value=null,e.hasNext=!1,e.hasCompleted=!1,e}return r.C6(e,t),e.prototype._subscribe=function(e){return this.hasError?(e.error(this.thrownError),i.y.EMPTY):this.hasCompleted&&this.hasNext?(e.next(this.value),e.complete(),i.y.EMPTY):t.prototype._subscribe.call(this,e)},e.prototype.next=function(t){this.hasCompleted||(this.value=t,this.hasNext=!0)},e.prototype.error=function(e){this.hasCompleted||t.prototype.error.call(this,e)},e.prototype.complete=function(){this.hasCompleted=!0,this.hasNext&&t.prototype.next.call(this,this.value),t.prototype.complete.call(this)},e}(o.B7)},27399:(t,e,n)=>{"use strict";n.d(e,{t:()=>a});var r=n(44693),o=n(47029),i=n(73404),a=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return r.C6(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new i.P;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(o.B7)},59038:(t,e,n)=>{"use strict";n.d(e,{E:()=>u,I:()=>r});var r,o=n(79058),i=n(78274),a=n(93033);r||(r={});var u=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return(0,i.of)(this.value);case"E":return(0,a.$)(this.error);case"C":return(0,o.I)()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return void 0!==e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}()},97188:(t,e,n)=>{"use strict";n.d(e,{c:()=>c}),n(13521),n(67536),n(44594);var r=n(96474),o=n(10075),i=n(19241),a=n(7336),u=n(47255),c=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,i=(0,o.u)(t,e,n);if(r?i.add(r.call(i,this.source)):i.add(this.source||u.$.useDeprecatedSynchronousErrorHandling&&!i.syncErrorThrowable?this._subscribe(i):this._trySubscribe(i)),u.$.useDeprecatedSynchronousErrorHandling&&i.syncErrorThrowable&&(i.syncErrorThrowable=!1,i.syncErrorThrown))throw i.syncErrorValue;return i},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){u.$.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),(0,r.H)(t)?t.error(e):console.warn(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=s(e))((function(e,r){var o;o=n.subscribe((function(e){try{t(e)}catch(t){r(t),o&&o.unsubscribe()}}),r,e)}))},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[i.s]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e{"use strict";n.d(e,{I:()=>i});var r=n(47255),o=n(95292),i={closed:!0,next:function(t){},error:function(t){if(r.$.useDeprecatedSynchronousErrorHandling)throw t;(0,o.T)(t)},complete:function(){}}},82896:(t,e,n)=>{"use strict";n.d(e,{E:()=>o});var r=n(44693),o=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(n(72687).v)},39384:(t,e,n)=>{"use strict";n.d(e,{m:()=>l}),n(67068),n(25226);var r=n(44693),o=n(47029),i=n(22310),a=n(64264),u=n(67038),c=n(73404),s=n(43444),l=function(t){function e(e,n,r){void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY);var o=t.call(this)||this;return o.scheduler=r,o._events=[],o._infiniteTimeWindow=!1,o._bufferSize=e<1?1:e,o._windowTime=n<1?1:n,n===Number.POSITIVE_INFINITY?(o._infiniteTimeWindow=!0,o.next=o.nextInfiniteTimeWindow):o.next=o.nextTimeWindow,o}return r.C6(e,t),e.prototype.nextInfiniteTimeWindow=function(e){if(!this.isStopped){var n=this._events;n.push(e),n.length>this._bufferSize&&n.shift()}t.prototype.next.call(this,e)},e.prototype.nextTimeWindow=function(e){this.isStopped||(this._events.push(new f(this._getNow(),e)),this._trimBufferThenGetEvents()),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){var e,n=this._infiniteTimeWindow,r=n?this._events:this._trimBufferThenGetEvents(),o=this.scheduler,i=r.length;if(this.closed)throw new c.P;if(this.isStopped||this.hasError?e=a.y.EMPTY:(this.observers.push(t),e=new s.Y(this,t)),o&&t.add(t=new u.YZ(t,o)),n)for(var l=0;le&&(i=Math.max(i,o-e)),i>0&&r.splice(0,i),r},e}(o.B7),f=function(){return function(t,e){this.time=t,this.value=e}}()},90480:(t,e,n)=>{"use strict";n.d(e,{_:()=>r});var r=function(){function t(e,n){void 0===n&&(n=t.now),this.SchedulerAction=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.SchedulerAction(this,t).schedule(n,e)},t.now=function(){return Date.now()},t}()},47029:(t,e,n)=>{"use strict";n.d(e,{B7:()=>f,PJ:()=>l}),n(44396);var r=n(44693),o=n(97188),i=n(72687),a=n(64264),u=n(73404),c=n(43444),s=n(36956),l=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return r.C6(e,t),e}(i.v),f=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return r.C6(e,t),e.prototype[s.D]=function(){return new l(this)},e.prototype.lift=function(t){var e=new p(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new u.P;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),o=0;o{"use strict";n.d(e,{Y:()=>o}),n(47818),n(67068);var r=n(44693),o=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return r.C6(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(n(64264).y)},72687:(t,e,n)=>{"use strict";n.d(e,{v:()=>f}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var r=n(44693),o=n(95120),i=n(78191),a=n(64264),u=n(36956),c=n(47255),s=n(95292);function l(t){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l(t)}var f=function(t){function e(n,r,o){var a=t.call(this)||this;switch(a.syncErrorValue=null,a.syncErrorThrown=!1,a.syncErrorThrowable=!1,a.isStopped=!1,arguments.length){case 0:a.destination=i.I;break;case 1:if(!n){a.destination=i.I;break}if("object"===l(n)){n instanceof e?(a.syncErrorThrowable=n.syncErrorThrowable,a.destination=n,n.add(a)):(a.syncErrorThrowable=!0,a.destination=new p(a,n));break}default:a.syncErrorThrowable=!0,a.destination=new p(a,n,r,o)}return a}return r.C6(e,t),e.prototype[u.D]=function(){return this},e.create=function(t,n,r){var o=new e(t,n,r);return o.syncErrorThrowable=!1,o},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=t,this},e}(a.y),p=function(t){function e(e,n,r,a){var u,c=t.call(this)||this;c._parentSubscriber=e;var s=c;return(0,o.T)(n)?u=n:n&&(u=n.next,r=n.error,a=n.complete,n!==i.I&&(s=Object.create(n),(0,o.T)(s.unsubscribe)&&c.add(s.unsubscribe.bind(s)),s.unsubscribe=c.unsubscribe.bind(c))),c._context=s,c._next=u,c._error=r,c._complete=a,c}return r.C6(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;c.$.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=c.$.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):(0,s.T)(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;(0,s.T)(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};c.$.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){if(this.unsubscribe(),c.$.useDeprecatedSynchronousErrorHandling)throw t;(0,s.T)(t)}},e.prototype.__tryOrSetError=function(t,e,n){if(!c.$.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(e){return c.$.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=e,t.syncErrorThrown=!0,!0):((0,s.T)(e),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(f)},64264:(t,e,n)=>{"use strict";n.d(e,{y:()=>c}),n(91621),n(27481),n(90105),n(98556),n(47818),n(14718),n(67068),n(13521),n(25766),n(92947);var r=n(17815),o=n(46775),i=n(95120),a=n(55758);function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}var c=function(){function t(t){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,t&&(this._ctorUnsubscribe=!0,this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var e;if(!this.closed){var n=this,u=n._parentOrParents,c=n._ctorUnsubscribe,l=n._unsubscribe,f=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,u instanceof t)u.remove(this);else if(null!==u)for(var p=0;p{"use strict";n.d(e,{$:()=>o});var r=!1,o={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){t&&(new Error).stack,r=t},get useDeprecatedSynchronousErrorHandling(){return r}}},24813:(t,e,n)=>{"use strict";n.d(e,{gn:()=>c,tS:()=>s,zA:()=>u});var r=n(44693),o=n(72687),i=n(97188),a=n(57839),u=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,n}return r.C6(e,t),e.prototype._next=function(t){this.parent.notifyNext(t)},e.prototype._error=function(t){this.parent.notifyError(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},e}(o.v),c=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.notifyNext=function(t){this.destination.next(t)},e.prototype.notifyError=function(t){this.destination.error(t)},e.prototype.notifyComplete=function(){this.destination.complete()},e}(o.v);function s(t,e){if(!e.closed){if(t instanceof i.c)return t.subscribe(e);var n;try{n=(0,a.i)(t)(e)}catch(t){e.error(t)}return n}}},64952:(t,e,n)=>{"use strict";n.d(e,{G:()=>c,f:()=>s});var r=n(44693),o=n(47029),i=n(97188),a=n(64264),u=n(20643),c=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return r.C6(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new a.y).add(this.source.subscribe(new l(this.getSubject(),this))),t.closed&&(this._connection=null,t=a.y.EMPTY)),t},e.prototype.refCount=function(){return(0,u.B)()(this)},e}(i.c),s=function(){var t=c.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:t._subscribe},_isComplete:{value:t._isComplete,writable:!0},getSubject:{value:t.getSubject},connect:{value:t.connect},refCount:{value:t.refCount}}}(),l=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.C6(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(o.PJ)},60685:(t,e,n)=>{"use strict";n.d(e,{ZS:()=>f,zV:()=>l}),n(14718),n(44396),n(13521),n(92947);var r=n(44693),o=n(11599),i=n(17815),a=n(82896),u=n(2455),c=n(95270),s={};function l(){for(var t=[],e=0;e{"use strict";n.d(e,{x:()=>i});var r=n(78274),o=n(97824);function i(){for(var t=[],e=0;e{"use strict";n.d(e,{v:()=>a});var r=n(97188),o=n(37055),i=n(79058);function a(t){return new r.c((function(e){var n;try{n=t()}catch(t){return void e.error(t)}return(n?(0,o.H)(n):(0,i.I)()).subscribe(e)}))}},79058:(t,e,n)=>{"use strict";n.d(e,{I:()=>i,w:()=>o});var r=n(97188),o=new r.c((function(t){return t.complete()}));function i(t){return t?function(t){return new r.c((function(e){return t.schedule((function(){return e.complete()}))}))}(t):o}},37055:(t,e,n)=>{"use strict";n.d(e,{H:()=>a});var r=n(97188),o=n(57839),i=n(64902);function a(t,e){return e?(0,i.c)(t,e):t instanceof r.c?t:new r.c((0,o.i)(t))}},95270:(t,e,n)=>{"use strict";n.d(e,{c:()=>a});var r=n(97188),o=n(64118),i=n(84047);function a(t,e){return e?(0,i.V)(t,e):new r.c((0,o.v)(t))}},27671:(t,e,n)=>{"use strict";n.d(e,{R:()=>u}),n(44396),n(13521),n(88315);var r=n(97188),o=n(17815),i=n(95120),a=n(20385);function u(t,e,n,s){return(0,i.T)(n)&&(s=n,n=void 0),s?u(t,e,n).pipe((0,a.T)((function(t){return(0,o.c)(t)?s.apply(void 0,t):s(t)}))):new r.c((function(r){c(t,e,(function(t){arguments.length>1?r.next(Array.prototype.slice.call(arguments)):r.next(t)}),r,n)}))}function c(t,e,n,r,o){var i;if(function(t){return t&&"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener}(t)){var a=t;t.addEventListener(e,n,o),i=function(){return a.removeEventListener(e,n,o)}}else if(function(t){return t&&"function"==typeof t.on&&"function"==typeof t.off}(t)){var u=t;t.on(e,n),i=function(){return u.off(e,n)}}else if(function(t){return t&&"function"==typeof t.addListener&&"function"==typeof t.removeListener}(t)){var s=t;t.addListener(e,n),i=function(){return s.removeListener(e,n)}}else{if(!t||!t.length)throw new TypeError("Invalid event target");for(var l=0,f=t.length;l{"use strict";n.d(e,{h:()=>u}),n(25226);var r=n(97188),o=n(11599),i=n(38948),a=n(95270);function u(){for(var t=[],e=0;e1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof c&&(n=t.pop()),null===u&&1===t.length&&t[0]instanceof r.c?t[0]:(0,i.U)(n)((0,a.c)(t,u))}},78274:(t,e,n)=>{"use strict";n.d(e,{of:()=>a});var r=n(11599),o=n(95270),i=n(84047);function a(){for(var t=[],e=0;e{"use strict";n.d(e,{O4:()=>c});var r=n(44693),o=n(17815),i=n(95270),a=n(82896),u=n(2455);function c(){for(var t=[],e=0;e{"use strict";n.d(e,{$:()=>o});var r=n(97188);function o(t,e){return e?new r.c((function(n){return e.schedule(i,0,{error:t,subscriber:n})})):new r.c((function(e){return e.error(t)}))}function i(t){var e=t.error;t.subscriber.error(e)}},40930:(t,e,n)=>{"use strict";n.d(e,{O:()=>u}),n(25226);var r=n(97188),o=n(58687),i=n(16745),a=n(11599);function u(t,e,n){void 0===t&&(t=0);var u=-1;return(0,i.k)(e)?u=Number(e)<1?1:Number(e):(0,a.m)(e)&&(n=e),(0,a.m)(n)||(n=o.b),new r.c((function(e){var r=(0,i.k)(t)?t:+t-n.now();return n.schedule(c,r,{index:0,period:u,subscriber:e})}))}function c(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}}},28124:(t,e,n)=>{"use strict";n.d(e,{ee:()=>l,yU:()=>s});var r=n(44693),o=n(95270),i=n(17815),a=n(72687),u=n(8034),c=n(24813);function s(){for(var t=[],e=0;ethis.index},t.prototype.hasCompleted=function(){return this.array.length===this.index},t}(),h=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.parent=n,o.observable=r,o.stillUnsubscribed=!0,o.buffer=[],o.isComplete=!1,o}return r.C6(e,t),e.prototype[u.lJ]=function(){return this},e.prototype.next=function(){var t=this.buffer;return 0===t.length&&this.isComplete?{value:null,done:!0}:{value:t.shift(),done:!1}},e.prototype.hasValue=function(){return this.buffer.length>0},e.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},e.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},e.prototype.notifyNext=function(t){this.buffer.push(t),this.parent.checkIterators()},e.prototype.subscribe=function(){return(0,c.tS)(this.observable,new c.zA(this))},e}(c.gn)},26540:(t,e,n)=>{"use strict";n.d(e,{W:()=>i});var r=n(44693),o=n(24813);function i(t){return function(e){var n=new a(t),r=e.lift(n);return n.caught=r}}var a=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.selector,this.caught))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.selector=n,o.caught=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(e){return void t.prototype.error.call(this,e)}this._unsubscribeAndRecycle();var r=new o.zA(this);this.add(r);var i=(0,o.tS)(n,r);i!==r&&this.add(i)}},e}(o.gn)},97824:(t,e,n)=>{"use strict";n.d(e,{K:()=>o});var r=n(38948);function o(){return(0,r.U)(1)}},59788:(t,e,n)=>{"use strict";n.d(e,{c:()=>c});var r=n(44693),o=n(58687),i=n(54948),a=n(72687),u=n(59038);function c(t,e){void 0===e&&(e=o.b);var n=(0,i.$)(t)?+t-e.now():Math.abs(t);return function(t){return t.lift(new s(n,e))}}var s=function(){function t(t,e){this.delay=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new l(t,this.delay,this.scheduler))},t}(),l=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return r.C6(e,t),e.dispatch=function(t){for(var e=t.source,n=e.queue,r=t.scheduler,o=t.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(t,i)}else this.unsubscribe(),e.active=!1},e.prototype._schedule=function(t){this.active=!0,this.destination.add(t.schedule(e.dispatch,this.delay,{source:this,destination:this.destination,scheduler:t}))},e.prototype.scheduleNotification=function(t){if(!0!==this.errored){var e=this.scheduler,n=new f(e.now()+this.delay,t);this.queue.push(n),!1===this.active&&this._schedule(e)}},e.prototype._next=function(t){this.scheduleNotification(u.E.createNext(t))},e.prototype._error=function(t){this.errored=!0,this.queue=[],this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.scheduleNotification(u.E.createComplete()),this.unsubscribe()},e}(a.v),f=function(){return function(t,e){this.time=t,this.notification=e}}()},17507:(t,e,n)=>{"use strict";n.d(e,{F:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.compare=t,this.keySelector=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.compare,this.keySelector))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return r.C6(e,t),e.prototype.compare=function(t,e){return t===e},e.prototype._next=function(t){var e;try{var n=this.keySelector;e=n?n(t):t}catch(t){return this.destination.error(t)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,e)}catch(t){return this.destination.error(t)}else this.hasKey=!0;r||(this.key=e,this.destination.next(t))},e}(o.v)},6245:(t,e,n)=>{"use strict";n.d(e,{p:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.predicate,this.thisArg))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}e&&this.destination.next(t)},e}(o.v)},40457:(t,e,n)=>{"use strict";n.d(e,{$:()=>c,k:()=>p}),n(14718),n(20363),n(13521),n(25766),n(44594),n(92947);var r=n(44693),o=n(72687),i=n(64264),a=n(97188),u=n(47029);function c(t,e,n,r){return function(o){return o.lift(new s(t,e,n,r))}}var s=function(){function t(t,e,n,r){this.keySelector=t,this.elementSelector=e,this.durationSelector=n,this.subjectSelector=r}return t.prototype.call=function(t,e){return e.subscribe(new l(t,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))},t}(),l=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;return a.keySelector=n,a.elementSelector=r,a.durationSelector=o,a.subjectSelector=i,a.groups=null,a.attemptedToUnsubscribe=!1,a.count=0,a}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.keySelector(t)}catch(t){return void this.error(t)}this._group(t,e)},e.prototype._group=function(t,e){var n=this.groups;n||(n=this.groups=new Map);var r,o=n.get(e);if(this.elementSelector)try{r=this.elementSelector(t)}catch(t){this.error(t)}else r=t;if(!o){o=this.subjectSelector?this.subjectSelector():new u.B7,n.set(e,o);var i=new p(e,o,this);if(this.destination.next(i),this.durationSelector){var a=void 0;try{a=this.durationSelector(new p(e,o))}catch(t){return void this.error(t)}this.add(a.subscribe(new f(e,o,this)))}}o.closed||o.next(r)},e.prototype._error=function(t){var e=this.groups;e&&(e.forEach((function(e,n){e.error(t)})),e.clear()),this.destination.error(t)},e.prototype._complete=function(){var t=this.groups;t&&(t.forEach((function(t,e){t.complete()})),t.clear()),this.destination.complete()},e.prototype.removeGroup=function(t){this.groups.delete(t)},e.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=!0,0===this.count&&t.prototype.unsubscribe.call(this))},e}(o.v),f=function(t){function e(e,n,r){var o=t.call(this,n)||this;return o.key=e,o.group=n,o.parent=r,o}return r.C6(e,t),e.prototype._next=function(t){this.complete()},e.prototype._unsubscribe=function(){var t=this.parent,e=this.key;this.key=this.parent=null,t&&t.removeGroup(e)},e}(o.v),p=function(t){function e(e,n,r){var o=t.call(this)||this;return o.key=e,o.groupSubject=n,o.refCountSubscription=r,o}return r.C6(e,t),e.prototype._subscribe=function(t){var e=new i.y,n=this.refCountSubscription,r=this.groupSubject;return n&&!n.closed&&e.add(new d(n)),e.add(r.subscribe(t)),e},e}(a.c),d=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,e.count++,n}return r.C6(e,t),e.prototype.unsubscribe=function(){var e=this.parent;e.closed||this.closed||(t.prototype.unsubscribe.call(this),e.count-=1,0===e.count&&e.attemptedToUnsubscribe&&e.unsubscribe())},e}(i.y)},20385:(t,e,n)=>{"use strict";n.d(e,{T:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.project,this.thisArg))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(o.v)},38948:(t,e,n)=>{"use strict";n.d(e,{U:()=>i}),n(25226);var r=n(75453),o=n(63242);function i(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),(0,r.ZZ)(o.D,t)}},75453:(t,e,n)=>{"use strict";n.d(e,{ZZ:()=>u,qI:()=>l}),n(25226);var r=n(44693),o=n(20385),i=n(37055),a=n(24813);function u(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(u((function(n,r){return(0,i.H)(t(n,r)).pipe((0,o.T)((function(t,o){return e(n,t,r,o)})))}),n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new c(t,n))})}var c=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.project,this.concurrent))},t}(),s=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=t.call(this,e)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return r.C6(e,t),e.prototype._next=function(t){this.active0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(a.gn),l=u},67038:(t,e,n)=>{"use strict";n.d(e,{QE:()=>a,YZ:()=>c});var r=n(44693),o=n(72687),i=n(59038);function a(t,e){return void 0===e&&(e=0),function(n){return n.lift(new u(t,e))}}var u=function(){function t(t,e){void 0===e&&(e=0),this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.scheduler,this.delay))},t}(),c=function(t){function e(e,n,r){void 0===r&&(r=0);var o=t.call(this,e)||this;return o.scheduler=n,o.delay=r,o}return r.C6(e,t),e.dispatch=function(t){var e=t.notification,n=t.destination;e.observe(n),this.unsubscribe()},e.prototype.scheduleMessage=function(t){this.destination.add(this.scheduler.schedule(e.dispatch,this.delay,new s(t,this.destination)))},e.prototype._next=function(t){this.scheduleMessage(i.E.createNext(t))},e.prototype._error=function(t){this.scheduleMessage(i.E.createError(t)),this.unsubscribe()},e.prototype._complete=function(){this.scheduleMessage(i.E.createComplete()),this.unsubscribe()},e}(o.v),s=function(){return function(t,e){this.notification=t,this.destination=e}}()},20643:(t,e,n)=>{"use strict";n.d(e,{B:()=>i});var r=n(44693),o=n(72687);function i(){return function(t){return t.lift(new a(t))}}var a=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new u(t,n),o=e.subscribe(r);return r.closed||(r.connection=n.connect()),o},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.C6(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(o.v)},37405:(t,e,n)=>{"use strict";n.d(e,{l:()=>a});var r=n(44693),o=n(47029),i=n(24813);function a(t){return function(e){return e.lift(new u(t,e))}}var u=function(){function t(t,e){this.notifier=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.notifier,this.source))},t}(),c=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.notifier=n,o.source=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.errors,r=this.retries,a=this.retriesSubscription;if(r)this.errors=void 0,this.retriesSubscription=void 0;else{n=new o.B7;try{r=(0,this.notifier)(n)}catch(e){return t.prototype.error.call(this,e)}a=(0,i.tS)(r,new i.zA(this))}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=a,n.next(e)}},e.prototype._unsubscribe=function(){var t=this.errors,e=this.retriesSubscription;t&&(t.unsubscribe(),this.errors=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype.notifyNext=function(){var t=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=t,this.source.subscribe(this)},e}(i.gn)},9099:(t,e,n)=>{"use strict";n.d(e,{t:()=>i}),n(91621),n(27481),n(90105),n(14718),n(25226),n(13521),n(25766),n(92947);var r=n(39384);function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function i(t,e,n){var i;return i=t&&"object"===o(t)?t:{bufferSize:t,windowTime:e,refCount:!1,scheduler:n},function(t){return t.lift(function(t){var e,n,o=t.bufferSize,i=void 0===o?Number.POSITIVE_INFINITY:o,a=t.windowTime,u=void 0===a?Number.POSITIVE_INFINITY:a,c=t.refCount,s=t.scheduler,l=0,f=!1,p=!1;return function(t){var o;l++,!e||f?(f=!1,e=new r.m(i,u,s),o=e.subscribe(this),n=t.subscribe({next:function(t){e.next(t)},error:function(t){f=!0,e.error(t)},complete:function(){p=!0,n=void 0,e.complete()}}),p&&(n=void 0)):o=e.subscribe(this),this.add((function(){l--,o.unsubscribe(),o=void 0,n&&!p&&c&&0===l&&(n.unsubscribe(),n=void 0,e=void 0)}))}}(i))}}},45893:(t,e,n)=>{"use strict";n.d(e,{n:()=>u});var r=n(44693),o=n(20385),i=n(37055),a=n(24813);function u(t,e){return"function"==typeof e?function(n){return n.pipe(u((function(n,r){return(0,i.H)(t(n,r)).pipe((0,o.T)((function(t,o){return e(n,t,r,o)})))})))}:function(e){return e.lift(new c(t))}}var c=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.project))},t}(),s=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return r.C6(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this._innerSub(e)},e.prototype._innerSub=function(t){var e=this.innerSubscription;e&&e.unsubscribe();var n=new a.zA(this),r=this.destination;r.add(n),this.innerSubscription=(0,a.tS)(t,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=void 0},e.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t){this.destination.next(t)},e}(a.gn)},78920:(t,e,n)=>{"use strict";n.d(e,{s:()=>u});var r=n(44693),o=n(72687),i=n(27943),a=n(79058);function u(t){return function(e){return 0===t?(0,a.I)():e.lift(new c(t))}}var c=function(){function t(t){if(this.total=t,this.total<0)throw new i.k}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.total))},t}(),s=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(o.v)},84047:(t,e,n)=>{"use strict";n.d(e,{V:()=>i});var r=n(97188),o=n(64264);function i(t,e){return new r.c((function(n){var r=new o.y,i=0;return r.add(e.schedule((function(){i!==t.length?(n.next(t[i++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}},37458:(t,e,n)=>{"use strict";n.d(e,{S:()=>a});var r=n(97188),o=n(64264),i=n(8034);function a(t,e){if(!t)throw new Error("Iterable cannot be null");return new r.c((function(n){var r,a=new o.y;return a.add((function(){r&&"function"==typeof r.return&&r.return()})),a.add(e.schedule((function(){r=t[i.lJ](),a.add(e.schedule((function(){if(!n.closed){var t,e;try{var o=r.next();t=o.value,e=o.done}catch(t){return void n.error(t)}e?n.complete():(n.next(t),this.schedule())}})))}))),a}))}},15737:(t,e,n)=>{"use strict";n.d(e,{x:()=>a});var r=n(97188),o=n(64264),i=n(19241);function a(t,e){return new r.c((function(n){var r=new o.y;return r.add(e.schedule((function(){var o=t[i.s]();r.add(o.subscribe({next:function(t){r.add(e.schedule((function(){return n.next(t)})))},error:function(t){r.add(e.schedule((function(){return n.error(t)})))},complete:function(){r.add(e.schedule((function(){return n.complete()})))}}))}))),r}))}},94479:(t,e,n)=>{"use strict";n.d(e,{P:()=>i});var r=n(97188),o=n(64264);function i(t,e){return new r.c((function(n){var r=new o.y;return r.add(e.schedule((function(){return t.then((function(t){r.add(e.schedule((function(){n.next(t),r.add(e.schedule((function(){return n.complete()})))})))}),(function(t){r.add(e.schedule((function(){return n.error(t)})))}))}))),r}))}},64902:(t,e,n)=>{"use strict";n.d(e,{c:()=>p}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var r=n(15737),o=n(94479),i=n(84047),a=n(37458),u=n(71206),c=n(40535),s=n(42736),l=n(46234);function f(t){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},f(t)}function p(t,e){if(null!=t){if((0,u.l)(t))return(0,r.x)(t,e);if((0,c.y)(t))return(0,o.P)(t,e);if((0,s.X)(t))return(0,i.V)(t,e);if((0,l.x)(t)||"string"==typeof t)return(0,a.S)(t,e)}throw new TypeError((null!==t&&f(t)||t)+" is not observable")}},12059:(t,e,n)=>{"use strict";n.d(e,{R:()=>o}),n(47818),n(67068);var r=n(44693),o=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return r.C6(e,t),e.prototype.schedule=function(t,e){if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this},e.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),setInterval(t.flush.bind(t,this),n)},e.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return e;clearInterval(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var n=!1,r=void 0;try{this.work(t)}catch(t){n=!0,r=!!t&&t||new Error(t)}if(n)return this.unsubscribe(),r},e.prototype._unsubscribe=function(){var t=this.id,e=this.scheduler,n=e.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null},e}(function(t){function e(e,n){return t.call(this)||this}return r.C6(e,t),e.prototype.schedule=function(t,e){return void 0===e&&(e=0),this},e}(n(64264).y))},75998:(t,e,n)=>{"use strict";n.d(e,{q:()=>i});var r=n(44693),o=n(90480),i=function(t){function e(n,r){void 0===r&&(r=o._.now);var i=t.call(this,n,(function(){return e.delegate&&e.delegate!==i?e.delegate.now():r()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return r.C6(e,t),e.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),e.delegate&&e.delegate!==this?e.delegate.schedule(n,r,o):t.prototype.schedule.call(this,n,r,o)},e.prototype.flush=function(t){var e=this.actions;if(this.active)e.push(t);else{var n;this.active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this.active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},e}(o._)},35947:(t,e,n)=>{"use strict";n.d(e,{I:()=>l,$:()=>s});var r=n(44693),o=(n(21894),n(13521),n(67536),1),i=function(){return Promise.resolve()}(),a={};function u(t){return t in a&&(delete a[t],!0)}var c=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.C6(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=(c=e.flush.bind(e,null),s=o++,a[s]=!0,i.then((function(){return u(s)&&c()})),s)));var c,s},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(u(n),e.scheduled=void 0)},e}(n(12059).R),s=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,o=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++r{"use strict";n.d(e,{E:()=>o,b:()=>i});var r=n(12059),o=new(n(75998).q)(r.R),i=o},22310:(t,e,n)=>{"use strict";n.d(e,{g:()=>a,T:()=>i});var r=n(44693),o=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.C6(e,t),e.prototype.schedule=function(e,n){return void 0===n&&(n=0),n>0?t.prototype.schedule.call(this,e,n):(this.delay=n,this.state=e,this.scheduler.flush(this),this)},e.prototype.execute=function(e,n){return n>0||this.closed?t.prototype.execute.call(this,e,n):this._execute(e,n)},e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?t.prototype.requestAsyncId.call(this,e,n,r):e.flush(this)},e}(n(12059).R),i=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e}(n(75998).q))(o),a=i},8034:(t,e,n)=>{"use strict";function r(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}n.d(e,{lJ:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var o=r()},19241:(t,e,n)=>{"use strict";n.d(e,{s:()=>r}),n(91621),n(27481),n(13521);var r=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}()},36956:(t,e,n)=>{"use strict";n.d(e,{D:()=>r}),n(91621),n(27481),n(13521);var r=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}()},27943:(t,e,n)=>{"use strict";n.d(e,{k:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return t.prototype=Object.create(Error.prototype),t}()},88509:(t,e,n)=>{"use strict";n.d(e,{G:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}return t.prototype=Object.create(Error.prototype),t}()},73404:(t,e,n)=>{"use strict";n.d(e,{P:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return t.prototype=Object.create(Error.prototype),t}()},54467:(t,e,n)=>{"use strict";n.d(e,{M:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return t.prototype=Object.create(Error.prototype),t}()},55758:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r}),n(57188),n(80404),n(18864),n(13521),n(88315);var r=function(){function t(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}return t.prototype=Object.create(Error.prototype),t}()},96474:(t,e,n)=>{"use strict";n.d(e,{H:()=>o});var r=n(72687);function o(t){for(;t;){var e=t,n=e.closed,o=e.destination,i=e.isStopped;if(n||i)return!1;t=o&&o instanceof r.v?o:null}return!0}},95292:(t,e,n)=>{"use strict";function r(t){setTimeout((function(){throw t}),0)}n.d(e,{T:()=>r})},63242:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{D:()=>r})},17815:(t,e,n)=>{"use strict";n.d(e,{c:()=>r});var r=function(){return Array.isArray||function(t){return t&&"number"==typeof t.length}}()},42736:(t,e,n)=>{"use strict";n.d(e,{X:()=>r});var r=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t}},54948:(t,e,n)=>{"use strict";function r(t){return t instanceof Date&&!isNaN(+t)}n.d(e,{$:()=>r})},95120:(t,e,n)=>{"use strict";function r(t){return"function"==typeof t}n.d(e,{T:()=>r})},71206:(t,e,n)=>{"use strict";n.d(e,{l:()=>o});var r=n(19241);function o(t){return t&&"function"==typeof t[r.s]}},46234:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(8034);function o(t){return t&&"function"==typeof t[r.lJ]}},16745:(t,e,n)=>{"use strict";n.d(e,{k:()=>o}),n(8933);var r=n(17815);function o(t){return!(0,r.c)(t)&&t-parseFloat(t)+1>=0}},46775:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return null!==t&&"object"===r(t)}n.d(e,{G:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947)},40535:(t,e,n)=>{"use strict";function r(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}n.d(e,{y:()=>r})},11599:(t,e,n)=>{"use strict";function r(t){return t&&"function"==typeof t.schedule}n.d(e,{m:()=>r})},3784:(t,e,n)=>{"use strict";function r(){}n.d(e,{l:()=>r})},80503:(t,e,n)=>{"use strict";function r(t,e){function n(){return!n.pred.apply(n.thisArg,arguments)}return n.pred=t,n.thisArg=e,n}n.d(e,{A:()=>r})},7336:(t,e,n)=>{"use strict";n.d(e,{F:()=>o,m:()=>i});var r=n(63242);function o(){for(var t=[],e=0;e{"use strict";n.d(e,{i:()=>p});var r=n(64118),o=n(42066),i=n(6261),a=n(49954),u=n(42736),c=n(40535),s=n(46775),l=n(8034),f=n(19241),p=function(t){if(t&&"function"==typeof t[f.s])return(0,a.X)(t);if((0,u.X)(t))return(0,r.v)(t);if((0,c.y)(t))return(0,o.F)(t);if(t&&"function"==typeof t[l.lJ])return(0,i.S)(t);var e=(0,s.G)(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+e+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")}},64118:(t,e,n)=>{"use strict";n.d(e,{v:()=>r});var r=function(t){return function(e){for(var n=0,r=t.length;n{"use strict";n.d(e,{S:()=>o});var r=n(8034),o=function(t){return function(e){for(var n=t[r.lJ]();;){var o=void 0;try{o=n.next()}catch(t){return e.error(t),e}if(o.done){e.complete();break}if(e.next(o.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e}}},49954:(t,e,n)=>{"use strict";n.d(e,{X:()=>o});var r=n(19241),o=function(t){return function(e){var n=t[r.s]();if("function"!=typeof n.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return n.subscribe(e)}}},42066:(t,e,n)=>{"use strict";n.d(e,{F:()=>o});var r=n(95292),o=function(t){return function(e){return t.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,r.T),e}}},2455:(t,e,n)=>{"use strict";n.d(e,{F:()=>u});var r=n(44693),o=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parent=e,o.outerValue=n,o.outerIndex=r,o.index=0,o}return r.C6(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n(72687).v),i=n(57839),a=n(97188);function u(t,e,n,r,u){if(void 0===u&&(u=new o(t,n,r)),!u.closed)return e instanceof a.c?e.subscribe(u):(0,i.i)(e)(u)}},10075:(t,e,n)=>{"use strict";n.d(e,{u:()=>a});var r=n(72687),o=n(36956),i=n(78191);function a(t,e,n){if(t){if(t instanceof r.v)return t;if(t[o.D])return t[o.D]()}return t||e||n?new r.v(t,e,n):new r.v(i.I)}},57532:(t,e,n)=>{"use strict";n.r(e),n.d(e,{audit:()=>i,auditTime:()=>l,buffer:()=>f,bufferCount:()=>y,bufferTime:()=>_,bufferToggle:()=>x,bufferWhen:()=>M,catchError:()=>D.W,combineAll:()=>z,combineLatest:()=>B,concat:()=>V,concatAll:()=>G.K,concatMap:()=>Y,concatMapTo:()=>W,count:()=>K,debounce:()=>Z,debounceTime:()=>tt,defaultIfEmpty:()=>ot,delay:()=>ut.c,delayWhen:()=>st,dematerialize:()=>ht,distinct:()=>mt,distinctUntilChanged:()=>_t.F,distinctUntilKeyChanged:()=>wt,elementAt:()=>xt,endWith:()=>Rt,every:()=>Mt,exhaust:()=>Dt,exhaustMap:()=>Ft,expand:()=>Vt,filter:()=>Ct.p,finalize:()=>Yt,find:()=>$t,findIndex:()=>Jt,first:()=>te,flatMap:()=>H.qI,groupBy:()=>ee.$,ignoreElements:()=>ne,isEmpty:()=>ie,last:()=>pe,map:()=>Ut.T,mapTo:()=>de,materialize:()=>me,max:()=>Ie,merge:()=>Pe,mergeAll:()=>Te.U,mergeMap:()=>H.ZZ,mergeMapTo:()=>Ae,mergeScan:()=>xe,min:()=>Me,multicast:()=>Ne,observeOn:()=>Le.QE,onErrorResumeNext:()=>ze,pairwise:()=>Be,partition:()=>He,pluck:()=>Ye,publish:()=>Ke,publishBehavior:()=>Qe,publishLast:()=>Je,publishReplay:()=>tn,race:()=>nn,reduce:()=>Ee,refCount:()=>hn.B,repeat:()=>rn,repeatWhen:()=>un,retry:()=>ln,retryWhen:()=>dn.l,sample:()=>yn,sampleTime:()=>gn,scan:()=>_e,sequenceEqual:()=>Sn,share:()=>Pn,shareReplay:()=>Tn.t,single:()=>An,skip:()=>Rn,skipLast:()=>Nn,skipUntil:()=>zn,skipWhile:()=>Bn,startWith:()=>Gn,subscribeOn:()=>Kn,switchAll:()=>Zn,switchMap:()=>Qn.n,switchMapTo:()=>Jn,take:()=>At.s,takeLast:()=>se,takeUntil:()=>Xn,takeWhile:()=>nr,tap:()=>ur,throttle:()=>fr,throttleTime:()=>hr,throwIfEmpty:()=>It,timeInterval:()=>br,timeout:()=>Pr,timeoutWith:()=>Cr,timestamp:()=>Tr,toArray:()=>kr,window:()=>Rr,windowCount:()=>Nr,windowTime:()=>zr,windowToggle:()=>Hr,windowWhen:()=>Kr,withLatestFrom:()=>Zr,zip:()=>eo,zipAll:()=>no});var r=n(44693),o=n(24813);function i(t){return function(e){return e.lift(new a(t))}}var a=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.durationSelector))},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r}return r.C6(e,t),e.prototype._next=function(t){if(this.value=t,this.hasValue=!0,!this.throttled){var e=void 0;try{e=(0,this.durationSelector)(t)}catch(t){return this.destination.error(t)}var n=(0,o.tS)(e,new o.zA(this));!n||n.closed?this.clearThrottle():this.add(this.throttled=n)}},e.prototype.clearThrottle=function(){var t=this,e=t.value,n=t.hasValue,r=t.throttled;r&&(this.remove(r),this.throttled=void 0,r.unsubscribe()),n&&(this.value=void 0,this.hasValue=!1,this.destination.next(e))},e.prototype.notifyNext=function(){this.clearThrottle()},e.prototype.notifyComplete=function(){this.clearThrottle()},e}(o.gn),c=n(58687),s=n(40930);function l(t,e){return void 0===e&&(e=c.b),i((function(){return(0,s.O)(t,e)}))}function f(t){return function(e){return e.lift(new p(t))}}var p=function(){function t(t){this.closingNotifier=t}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.closingNotifier))},t}(),d=function(t){function e(e,n){var r=t.call(this,e)||this;return r.buffer=[],r.add((0,o.tS)(n,new o.zA(r))),r}return r.C6(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype.notifyNext=function(){var t=this.buffer;this.buffer=[],this.destination.next(t)},e}(o.gn),h=(n(67068),n(72687));function y(t,e){return void 0===e&&(e=null),function(n){return n.lift(new v(t,e))}}var v=function(){function t(t,e){this.bufferSize=t,this.startBufferEvery=e,this.subscriberClass=e&&t!==e?g:m}return t.prototype.call=function(t,e){return e.subscribe(new this.subscriberClass(t,this.bufferSize,this.startBufferEvery))},t}(),m=function(t){function e(e,n){var r=t.call(this,e)||this;return r.bufferSize=n,r.buffer=[],r}return r.C6(e,t),e.prototype._next=function(t){var e=this.buffer;e.push(t),e.length==this.bufferSize&&(this.destination.next(e),this.buffer=[])},e.prototype._complete=function(){var e=this.buffer;e.length>0&&this.destination.next(e),t.prototype._complete.call(this)},e}(h.v),g=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.bufferSize=n,o.startBufferEvery=r,o.buffers=[],o.count=0,o}return r.C6(e,t),e.prototype._next=function(t){var e=this,n=e.bufferSize,r=e.startBufferEvery,o=e.buffers,i=e.count;this.count++,i%r==0&&o.push([]);for(var a=o.length;a--;){var u=o[a];u.push(t),u.length===n&&(o.splice(a,1),this.destination.next(u))}},e.prototype._complete=function(){for(var e=this.buffers,n=this.destination;e.length>0;){var r=e.shift();r.length>0&&n.next(r)}t.prototype._complete.call(this)},e}(h.v),b=(n(47818),n(25226),n(11599));function _(t){var e=arguments.length,n=c.b;(0,b.m)(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],e--);var r=null;e>=2&&(r=arguments[1]);var o=Number.POSITIVE_INFINITY;return e>=3&&(o=arguments[2]),function(e){return e.lift(new w(t,r,o,n))}}var w=function(){function t(t,e,n,r){this.bufferTimeSpan=t,this.bufferCreationInterval=e,this.maxBufferSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new C(t,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},t}(),S=function(){return function(){this.buffer=[]}}(),C=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;a.bufferTimeSpan=n,a.bufferCreationInterval=r,a.maxBufferSize=o,a.scheduler=i,a.contexts=[];var u=a.openContext();if(a.timespanOnly=null==r||r<0,a.timespanOnly){var c={subscriber:a,context:u,bufferTimeSpan:n};a.add(u.closeAction=i.schedule(E,n,c))}else{var s={subscriber:a,context:u},l={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:a,scheduler:i};a.add(u.closeAction=i.schedule(O,n,s)),a.add(i.schedule(I,r,l))}return a}return r.C6(e,t),e.prototype._next=function(t){for(var e,n=this.contexts,r=n.length,o=0;o0;){var r=e.shift();n.next(r.buffer)}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.contexts=null},e.prototype.onBufferFull=function(t){this.closeContext(t);var e=t.closeAction;if(e.unsubscribe(),this.remove(e),!this.closed&&this.timespanOnly){t=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:t,bufferTimeSpan:n};this.add(t.closeAction=this.scheduler.schedule(E,n,r))}},e.prototype.openContext=function(){var t=new S;return this.contexts.push(t),t},e.prototype.closeContext=function(t){this.destination.next(t.buffer);var e=this.contexts;(e?e.indexOf(t):-1)>=0&&e.splice(e.indexOf(t),1)},e}(h.v);function E(t){var e=t.subscriber,n=t.context;n&&e.closeContext(n),e.closed||(t.context=e.openContext(),t.context.closeAction=this.schedule(t,t.bufferTimeSpan))}function I(t){var e=t.bufferCreationInterval,n=t.bufferTimeSpan,r=t.subscriber,o=t.scheduler,i=r.openContext();r.closed||(r.add(i.closeAction=o.schedule(O,n,{subscriber:r,context:i})),this.schedule(t,e))}function O(t){var e=t.subscriber,n=t.context;e.closeContext(n)}var P=n(64264),T=n(2455),A=n(82896);function x(t,e){return function(n){return n.lift(new k(t,e))}}var k=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new R(t,this.openings,this.closingSelector))},t}(),R=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.closingSelector=r,o.contexts=[],o.add((0,T.F)(o,n)),o}return r.C6(e,t),e.prototype._next=function(t){for(var e=this.contexts,n=e.length,r=0;r0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts;e.length>0;){var n=e.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e){t?this.closeBuffer(t):this.openBuffer(e)},e.prototype.notifyComplete=function(t){this.closeBuffer(t.context)},e.prototype.openBuffer=function(t){try{var e=this.closingSelector.call(this,t);e&&this.trySubscribe(e)}catch(t){this._error(t)}},e.prototype.closeBuffer=function(t){var e=this.contexts;if(e&&t){var n=t.buffer,r=t.subscription;this.destination.next(n),e.splice(e.indexOf(t),1),this.remove(r),r.unsubscribe()}},e.prototype.trySubscribe=function(t){var e=this.contexts,n=new P.y,r={buffer:[],subscription:n};e.push(r);var o=(0,T.F)(this,t,r);!o||o.closed?this.closeBuffer(r):(o.context=r,this.add(o),n.add(o))},e}(A.E);function M(t){return function(e){return e.lift(new j(t))}}var j=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new N(t,this.closingSelector))},t}(),N=function(t){function e(e,n){var r=t.call(this,e)||this;return r.closingSelector=n,r.subscribing=!1,r.openBuffer(),r}return r.C6(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype._complete=function(){var e=this.buffer;e&&this.destination.next(e),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.buffer=void 0,this.subscribing=!1},e.prototype.notifyNext=function(){this.openBuffer()},e.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},e.prototype.openBuffer=function(){var t=this.closingSubscription;t&&(this.remove(t),t.unsubscribe());var e,n=this.buffer;this.buffer&&this.destination.next(n),this.buffer=[];try{e=(0,this.closingSelector)()}catch(t){return this.error(t)}t=new P.y,this.closingSubscription=t,this.add(t),this.subscribing=!0,t.add((0,o.tS)(e,new o.zA(this))),this.subscribing=!1},e}(o.gn),D=n(26540),L=n(60685);function z(t){return function(e){return e.lift(new L.ZS(t))}}n(98556),n(44396);var U=n(17815),F=n(37055);function B(){for(var t=[],e=0;e=2;return function(r){return r.pipe((0,Ct.p)((function(e,n){return n===t})),(0,At.s)(1),n?ot(e):It((function(){return new St.k})))}}var kt=n(78274);function Rt(){for(var t=[],e=0;e0&&this._next(t.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},e}(o.gn);function Yt(t){return function(e){return e.lift(new Wt(t))}}var Wt=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Kt(t,this.callback))},t}(),Kt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new P.y(n)),r}return r.C6(e,t),e}(h.v);function $t(t,e){if("function"!=typeof t)throw new TypeError("predicate is not a function");return function(n){return n.lift(new Qt(t,n,!1,e))}}var Qt=function(){function t(t,e,n,r){this.predicate=t,this.source=e,this.yieldIndex=n,this.thisArg=r}return t.prototype.call=function(t,e){return e.subscribe(new Zt(t,this.predicate,this.source,this.yieldIndex,this.thisArg))},t}(),Zt=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;return a.predicate=n,a.source=r,a.yieldIndex=o,a.thisArg=i,a.index=0,a}return r.C6(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete(),this.unsubscribe()},e.prototype._next=function(t){var e=this.predicate,n=this.thisArg,r=this.index++;try{e.call(n||this,t,r,this.source)&&this.notifyComplete(this.yieldIndex?r:t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},e}(h.v);function Jt(t,e){return function(n){return n.lift(new Qt(t,n,!0,e))}}var Xt=n(63242);function te(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?(0,Ct.p)((function(e,n){return t(e,n,r)})):Xt.D,(0,At.s)(1),n?ot(e):It((function(){return new Et.G})))}}var ee=n(40457);function ne(){return function(t){return t.lift(new re)}}var re=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new oe(t))},t}(),oe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype._next=function(t){},e}(h.v);function ie(){return function(t){return t.lift(new ae)}}var ae=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ue(t))},t}(),ue=function(t){function e(e){return t.call(this,e)||this}return r.C6(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype._next=function(t){this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(h.v),ce=n(79058);function se(t){return function(e){return 0===t?(0,ce.I)():e.lift(new le(t))}}var le=function(){function t(t){if(this.total=t,this.total<0)throw new St.k}return t.prototype.call=function(t,e){return e.subscribe(new fe(t,this.total))},t}(),fe=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,o=0;o=2;return function(r){return r.pipe(t?(0,Ct.p)((function(e,n){return t(e,n,r)})):Xt.D,se(1),n?ot(e):It((function(){return new Et.G})))}}function de(t){return function(e){return e.lift(new he(t))}}var he=function(){function t(t){this.value=t}return t.prototype.call=function(t,e){return e.subscribe(new ye(t,this.value))},t}(),ye=function(t){function e(e,n){var r=t.call(this,e)||this;return r.value=n,r}return r.C6(e,t),e.prototype._next=function(t){this.destination.next(this.value)},e}(h.v),ve=n(59038);function me(){return function(t){return t.lift(new ge)}}var ge=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new be(t))},t}(),be=function(t){function e(e){return t.call(this,e)||this}return r.C6(e,t),e.prototype._next=function(t){this.destination.next(ve.E.createNext(t))},e.prototype._error=function(t){var e=this.destination;e.next(ve.E.createError(t)),e.complete()},e.prototype._complete=function(){var t=this.destination;t.next(ve.E.createComplete()),t.complete()},e}(h.v);function _e(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new we(t,e,n))}}var we=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new Se(t,this.accumulator,this.seed,this.hasSeed))},t}(),Se=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i.accumulator=n,i._seed=r,i.hasSeed=o,i.index=0,i}return r.C6(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(t){this.destination.error(t)}this.seed=e,this.destination.next(e)},e}(h.v),Ce=n(7336);function Ee(t,e){return arguments.length>=2?function(n){return(0,Ce.F)(_e(t,e),se(1),ot(e))(n)}:function(e){return(0,Ce.F)(_e((function(e,n,r){return t(e,n,r+1)})),se(1))(e)}}function Ie(t){return Ee("function"==typeof t?function(e,n){return t(e,n)>0?e:n}:function(t,e){return t>e?t:e})}var Oe=n(5475);function Pe(){for(var t=[],e=0;e0?this._next(t.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},e}(o.gn);function Me(t){return Ee("function"==typeof t?function(e,n){return t(e,n)<0?e:n}:function(t,e){return t-1&&(this.count=n-1),e.subscribe(this._unsubscribeAndRecycle())}},e}(h.v);function un(t){return function(e){return e.lift(new cn(t))}}var cn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new sn(t,this.notifier,e))},t}(),sn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.notifier=n,o.source=r,o.sourceIsBeingSubscribedTo=!0,o}return r.C6(e,t),e.prototype.notifyNext=function(){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},e.prototype.notifyComplete=function(){if(!1===this.sourceIsBeingSubscribedTo)return t.prototype.complete.call(this)},e.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return t.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next(void 0)}},e.prototype._unsubscribe=function(){var t=this.notifications,e=this.retriesSubscription;t&&(t.unsubscribe(),this.notifications=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype._unsubscribeAndRecycle=function(){var e=this._unsubscribe;return this._unsubscribe=null,t.prototype._unsubscribeAndRecycle.call(this),this._unsubscribe=e,this},e.prototype.subscribeToRetries=function(){var e;this.notifications=new We.B7;try{e=(0,this.notifier)(this.notifications)}catch(e){return t.prototype.complete.call(this)}this.retries=e,this.retriesSubscription=(0,o.tS)(e,new o.zA(this))},e}(o.gn);function ln(t){return void 0===t&&(t=-1),function(e){return e.lift(new fn(t,e))}}var fn=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new pn(t,this.count,this.source))},t}(),pn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.count=n,o.source=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return t.prototype.error.call(this,e);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},e}(h.v),dn=n(37405),hn=n(20643);function yn(t){return function(e){return e.lift(new vn(t))}}var vn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new mn(t),r=e.subscribe(n);return r.add((0,o.tS)(this.notifier,new o.zA(n))),r},t}(),mn=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.hasValue=!1,e}return r.C6(e,t),e.prototype._next=function(t){this.value=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},e}(o.gn);function gn(t,e){return void 0===e&&(e=c.b),function(n){return n.lift(new bn(t,e))}}var bn=function(){function t(t,e){this.period=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new _n(t,this.period,this.scheduler))},t}(),_n=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.period=n,o.scheduler=r,o.hasValue=!1,o.add(r.schedule(wn,n,{subscriber:o,period:n})),o}return r.C6(e,t),e.prototype._next=function(t){this.lastValue=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},e}(h.v);function wn(t){var e=t.subscriber,n=t.period;e.notifyNext(),this.schedule(t,n)}function Sn(t,e){return function(n){return n.lift(new Cn(t,e))}}var Cn=function(){function t(t,e){this.compareTo=t,this.comparator=e}return t.prototype.call=function(t,e){return e.subscribe(new En(t,this.compareTo,this.comparator))},t}(),En=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.compareTo=n,o.comparator=r,o._a=[],o._b=[],o._oneComplete=!1,o.destination.add(n.subscribe(new In(e,o))),o}return r.C6(e,t),e.prototype._next=function(t){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(t),this.checkValues())},e.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0,this.unsubscribe()},e.prototype.checkValues=function(){for(var t=this,e=t._a,n=t._b,r=t.comparator;e.length>0&&n.length>0;){var o=e.shift(),i=n.shift(),a=!1;try{a=r?r(o,i):o===i}catch(t){this.destination.error(t)}a||this.emit(!1)}},e.prototype.emit=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype.nextB=function(t){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(t),this.checkValues())},e.prototype.completeB=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},e}(h.v),In=function(t){function e(e,n){var r=t.call(this,e)||this;return r.parent=n,r}return r.C6(e,t),e.prototype._next=function(t){this.parent.nextB(t)},e.prototype._error=function(t){this.parent.error(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.completeB(),this.unsubscribe()},e}(h.v);function On(){return new We.B7}function Pn(){return function(t){return(0,hn.B)()(Ne(On)(t))}}var Tn=n(9099);function An(t){return function(e){return e.lift(new xn(t,e))}}var xn=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new kn(t,this.predicate,this.source))},t}(),kn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.predicate=n,o.source=r,o.seenValue=!1,o.index=0,o}return r.C6(e,t),e.prototype.applySingleValue=function(t){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=t)},e.prototype._next=function(t){var e=this.index++;this.predicate?this.tryNext(t,e):this.applySingleValue(t)},e.prototype.tryNext=function(t,e){try{this.predicate(t,e,this.source)&&this.applySingleValue(t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){var t=this.destination;this.index>0?(t.next(this.seenValue?this.singleValue:void 0),t.complete()):t.error(new Et.G)},e}(h.v);function Rn(t){return function(e){return e.lift(new Mn(t))}}var Mn=function(){function t(t){this.total=t}return t.prototype.call=function(t,e){return e.subscribe(new jn(t,this.total))},t}(),jn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){++this.count>this.total&&this.destination.next(t)},e}(h.v);function Nn(t){return function(e){return e.lift(new Dn(t))}}var Dn=function(){function t(t){if(this._skipCount=t,this._skipCount<0)throw new St.k}return t.prototype.call=function(t,e){return 0===this._skipCount?e.subscribe(new h.v(t)):e.subscribe(new Ln(t,this._skipCount))},t}(),Ln=function(t){function e(e,n){var r=t.call(this,e)||this;return r._skipCount=n,r._count=0,r._ring=new Array(n),r}return r.C6(e,t),e.prototype._next=function(t){var e=this._skipCount,n=this._count++;if(n0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,o=this.windows,i=o.length,a=0;a=0&&u%e==0&&!this.closed&&o.shift().complete(),++this.count%e==0&&!this.closed){var c=new We.B7;o.push(c),n.next(c)}},e.prototype._error=function(t){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().complete();this.destination.complete()},e.prototype._unsubscribe=function(){this.count=0,this.windows=null},e}(h.v);function zr(t){var e=c.b,n=null,r=Number.POSITIVE_INFINITY;return(0,b.m)(arguments[3])&&(e=arguments[3]),(0,b.m)(arguments[2])?e=arguments[2]:(0,Yn.k)(arguments[2])&&(r=Number(arguments[2])),(0,b.m)(arguments[1])?e=arguments[1]:(0,Yn.k)(arguments[1])&&(n=Number(arguments[1])),function(o){return o.lift(new Ur(t,n,r,e))}}var Ur=function(){function t(t,e,n,r){this.windowTimeSpan=t,this.windowCreationInterval=e,this.maxWindowSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new Br(t,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},t}(),Fr=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._numberOfNextedValues=0,e}return r.C6(e,t),e.prototype.next=function(e){this._numberOfNextedValues++,t.prototype.next.call(this,e)},Object.defineProperty(e.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),e}(We.B7),Br=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;a.destination=e,a.windowTimeSpan=n,a.windowCreationInterval=r,a.maxWindowSize=o,a.scheduler=i,a.windows=[];var u=a.openWindow();if(null!==r&&r>=0){var c={subscriber:a,window:u,context:null},s={windowTimeSpan:n,windowCreationInterval:r,subscriber:a,scheduler:i};a.add(i.schedule(Gr,n,c)),a.add(i.schedule(Vr,r,s))}else{var l={subscriber:a,window:u,windowTimeSpan:n};a.add(i.schedule(qr,n,l))}return a}return r.C6(e,t),e.prototype._next=function(t){for(var e=this.windows,n=e.length,r=0;r=this.maxWindowSize&&this.closeWindow(o))}},e.prototype._error=function(t){for(var e=this.windows;e.length>0;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){for(var t=this.windows;t.length>0;){var e=t.shift();e.closed||e.complete()}this.destination.complete()},e.prototype.openWindow=function(){var t=new Fr;return this.windows.push(t),this.destination.next(t),t},e.prototype.closeWindow=function(t){t.complete();var e=this.windows;e.splice(e.indexOf(t),1)},e}(h.v);function qr(t){var e=t.subscriber,n=t.windowTimeSpan,r=t.window;r&&e.closeWindow(r),t.window=e.openWindow(),this.schedule(t,n)}function Vr(t){var e=t.windowTimeSpan,n=t.subscriber,r=t.scheduler,o=t.windowCreationInterval,i=n.openWindow(),a=this,u={action:a,subscription:null},c={subscriber:n,window:i,context:u};u.subscription=r.schedule(Gr,e,c),a.add(u.subscription),a.schedule(t,o)}function Gr(t){var e=t.subscriber,n=t.window,r=t.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),e.closeWindow(n)}function Hr(t,e){return function(n){return n.lift(new Yr(t,e))}}var Yr=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new Wr(t,this.openings,this.closingSelector))},t}(),Wr=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.openings=n,o.closingSelector=r,o.contexts=[],o.add(o.openSubscription=(0,T.F)(o,n,n)),o}return r.C6(e,t),e.prototype._next=function(t){var e=this.contexts;if(e)for(var n=e.length,r=0;r0){var o=r.indexOf(n);-1!==o&&r.splice(o,1)}},e.prototype.notifyComplete=function(){},e.prototype._next=function(t){if(0===this.toRespond.length){var e=[t].concat(this.values);this.project?this._tryProject(e):this.destination.next(e)}},e.prototype._tryProject=function(t){var e;try{e=this.project.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(A.E),to=n(28124);function eo(){for(var t=[],e=0;e{"use strict";n.d(e,{C6:()=>o}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var r=function(t,e){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},r(t,e)};function o(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}},96150:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(21894),n(13521),n(25766),n(92947),t.exports=function(t,e,n,o){var i=n?n.call(o,t,e):void 0;if(void 0!==i)return!!i;if(t===e)return!0;if("object"!==r(t)||!t||"object"!==r(e)||!e)return!1;var a=Object.keys(t),u=Object.keys(e);if(a.length!==u.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(e),s=0;s{"use strict";n(47818),n(44396),t.exports=function(t,e){if("string"!=typeof t||"string"!=typeof e)throw new TypeError("Expected the arguments to be of type `string`");if(""===e)return[t];var n=t.indexOf(e);return-1===n?[t]:[t.slice(0,n),t.slice(n+e.length)]}},23081:(t,e,n)=>{"use strict";n(13521),n(88315),n(53618),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}},35476:(t,e,n)=>{var r=n(11055),o=n(79269),i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not a function")}},68634:(t,e,n)=>{var r=n(11547),o=n(79269),i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not a constructor")}},1520:(t,e,n)=>{var r=n(11055),o=String,i=TypeError;t.exports=function(t){if("object"==typeof t||r(t))return t;throw i("Can't set "+o(t)+" as a prototype")}},44595:(t,e,n)=>{var r=n(39189),o=n(32814),i=n(59143).f,a=r("unscopables"),u=Array.prototype;null==u[a]&&i(u,a,{configurable:!0,value:o(null)}),t.exports=function(t){u[a][t]=!0}},78839:(t,e,n)=>{"use strict";var r=n(65877).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},37809:(t,e,n)=>{var r=n(47931),o=TypeError;t.exports=function(t,e){if(r(e,t))return t;throw o("Incorrect invocation")}},90649:(t,e,n)=>{var r=n(96692),o=String,i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not an object")}},69141:t=>{t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},65642:(t,e,n)=>{var r=n(79061);t.exports=r((function(){if("function"==typeof ArrayBuffer){var t=new ArrayBuffer(8);Object.isExtensible(t)&&Object.defineProperty(t,"a",{value:8})}}))},70668:(t,e,n)=>{"use strict";var r=n(21833),o=n(38982),i=n(4426),a=n(69141),u=n(92684),c=n(69193),s=n(61548),l=n(14101),f=n(79061),p=n(37809),d=n(91129),h=n(99536),y=n(2042),v=n(13228),m=n(52473),g=n(26213),b=n(47210).f,_=n(70419),w=n(10301),S=n(49233),C=n(58319),E=u.PROPER,I=u.CONFIGURABLE,O="ArrayBuffer",P="DataView",T="prototype",A="Wrong index",x=C.getterFor(O),k=C.getterFor(P),R=C.set,M=r[O],j=M,N=j&&j[T],D=r[P],L=D&&D[T],z=Object.prototype,U=r.Array,F=r.RangeError,B=o(_),q=o([].reverse),V=v.pack,G=v.unpack,H=function(t){return[255&t]},Y=function(t){return[255&t,t>>8&255]},W=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},K=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},$=function(t){return V(t,23,4)},Q=function(t){return V(t,52,8)},Z=function(t,e,n){s(t[T],e,{configurable:!0,get:function(){return n(this)[e]}})},J=function(t,e,n,r){var o=y(n),i=k(t);if(o+e>i.byteLength)throw F(A);var a=i.bytes,u=o+i.byteOffset,c=w(a,u,u+e);return r?c:q(c)},X=function(t,e,n,r,o,i){var a=y(n),u=k(t);if(a+e>u.byteLength)throw F(A);for(var c=u.bytes,s=a+u.byteOffset,l=r(+o),f=0;frt;)(et=nt[rt++])in j||c(j,et,M[et]);N.constructor=j}g&&m(L)!==z&&g(L,z);var ot=new D(new j(2)),it=o(L.setInt8);ot.setInt8(0,2147483648),ot.setInt8(1,2147483649),!ot.getInt8(0)&&ot.getInt8(1)||l(L,{setInt8:function(t,e){it(this,t,e<<24>>24)},setUint8:function(t,e){it(this,t,e<<24>>24)}},{unsafe:!0})}else N=(j=function(t){p(this,N);var e=y(t);R(this,{type:O,bytes:B(U(e),0),byteLength:e}),i||(this.byteLength=e,this.detached=!1)})[T],L=(D=function(t,e,n){p(this,L),p(t,N);var r=x(t),o=r.byteLength,a=d(e);if(a<0||a>o)throw F("Wrong offset");if(a+(n=void 0===n?o-a:h(n))>o)throw F("Wrong length");R(this,{type:P,buffer:t,byteLength:n,byteOffset:a,bytes:r.bytes}),i||(this.buffer=t,this.byteLength=n,this.byteOffset=a)})[T],i&&(Z(j,"byteLength",x),Z(D,"buffer",k),Z(D,"byteLength",k),Z(D,"byteOffset",k)),l(L,{getInt8:function(t){return J(this,1,t)[0]<<24>>24},getUint8:function(t){return J(this,1,t)[0]},getInt16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return e[1]<<8|e[0]},getInt32:function(t){return K(J(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return K(J(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return G(J(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return G(J(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,e){X(this,1,t,H,e)},setUint8:function(t,e){X(this,1,t,H,e)},setInt16:function(t,e){X(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,e){X(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,e){X(this,4,t,W,e,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,e){X(this,4,t,W,e,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,e){X(this,4,t,$,e,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,e){X(this,8,t,Q,e,arguments.length>2?arguments[2]:void 0)}});S(j,O),S(D,P),t.exports={ArrayBuffer:j,DataView:D}},70419:(t,e,n)=>{"use strict";var r=n(50775),o=n(79036),i=n(12244);t.exports=function(t){for(var e=r(this),n=i(e),a=arguments.length,u=o(a>1?arguments[1]:void 0,n),c=a>2?arguments[2]:void 0,s=void 0===c?n:o(c,n);s>u;)e[u++]=t;return e}},9877:(t,e,n)=>{"use strict";var r=n(31567).forEach,o=n(46644)("forEach");t.exports=o?[].forEach:function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}},36658:(t,e,n)=>{"use strict";var r=n(67302),o=n(44931),i=n(50775),a=n(33809),u=n(77847),c=n(11547),s=n(12244),l=n(25762),f=n(81963),p=n(16421),d=Array;t.exports=function(t){var e=i(t),n=c(this),h=arguments.length,y=h>1?arguments[1]:void 0,v=void 0!==y;v&&(y=r(y,h>2?arguments[2]:void 0));var m,g,b,_,w,S,C=p(e),E=0;if(!C||this===d&&u(C))for(m=s(e),g=n?new this(m):d(m);m>E;E++)S=v?y(e[E],E):e[E],l(g,E,S);else for(w=(_=f(e,C)).next,g=n?new this:[];!(b=o(w,_)).done;E++)S=v?a(_,y,[b.value,E],!0):b.value,l(g,E,S);return g.length=E,g}},20895:(t,e,n)=>{var r=n(4395),o=n(79036),i=n(12244),a=function(t){return function(e,n,a){var u,c=r(e),s=i(c),l=o(a,s);if(t&&n!=n){for(;s>l;)if((u=c[l++])!=u)return!0}else for(;s>l;l++)if((t||l in c)&&c[l]===n)return t||l||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},31567:(t,e,n)=>{var r=n(67302),o=n(38982),i=n(7461),a=n(50775),u=n(12244),c=n(88627),s=o([].push),l=function(t){var e=1==t,n=2==t,o=3==t,l=4==t,f=6==t,p=7==t,d=5==t||f;return function(h,y,v,m){for(var g,b,_=a(h),w=i(_),S=r(y,v),C=u(w),E=0,I=m||c,O=e?I(h,C):n||p?I(h,0):void 0;C>E;E++)if((d||E in w)&&(b=S(g=w[E],E,_),t))if(e)O[E]=b;else if(b)switch(t){case 3:return!0;case 5:return g;case 6:return E;case 2:s(O,g)}else switch(t){case 4:return!1;case 7:s(O,g)}return f?-1:o||l?l:O}};t.exports={forEach:l(0),map:l(1),filter:l(2),some:l(3),every:l(4),find:l(5),findIndex:l(6),filterReject:l(7)}},37041:(t,e,n)=>{"use strict";var r=n(33247),o=n(4395),i=n(91129),a=n(12244),u=n(46644),c=Math.min,s=[].lastIndexOf,l=!!s&&1/[1].lastIndexOf(1,-0)<0,f=u("lastIndexOf"),p=l||!f;t.exports=p?function(t){if(l)return r(s,this,arguments)||0;var e=o(this),n=a(e),u=n-1;for(arguments.length>1&&(u=c(u,i(arguments[1]))),u<0&&(u=n+u);u>=0;u--)if(u in e&&e[u]===t)return u||0;return-1}:s},20423:(t,e,n)=>{var r=n(79061),o=n(39189),i=n(36918),a=o("species");t.exports=function(t){return i>=51||!r((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},46644:(t,e,n)=>{"use strict";var r=n(79061);t.exports=function(t,e){var n=[][t];return!!n&&r((function(){n.call(null,e||function(){return 1},1)}))}},41909:(t,e,n)=>{"use strict";var r=n(4426),o=n(57886),i=TypeError,a=Object.getOwnPropertyDescriptor,u=r&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(t){return t instanceof TypeError}}();t.exports=u?function(t,e){if(o(t)&&!a(t,"length").writable)throw i("Cannot set read only .length");return t.length=e}:function(t,e){return t.length=e}},10301:(t,e,n)=>{var r=n(79036),o=n(12244),i=n(25762),a=Array,u=Math.max;t.exports=function(t,e,n){for(var c=o(t),s=r(e,c),l=r(void 0===n?c:n,c),f=a(u(l-s,0)),p=0;s{var r=n(38982);t.exports=r([].slice)},84326:(t,e,n)=>{var r=n(10301),o=Math.floor,i=function(t,e){var n=t.length,c=o(n/2);return n<8?a(t,e):u(t,i(r(t,0,c),e),i(r(t,c),e),e)},a=function(t,e){for(var n,r,o=t.length,i=1;i0;)t[r]=t[--r];r!==i++&&(t[r]=n)}return t},u=function(t,e,n,r){for(var o=e.length,i=n.length,a=0,u=0;a{var r=n(57886),o=n(11547),i=n(96692),a=n(39189)("species"),u=Array;t.exports=function(t){var e;return r(t)&&(e=t.constructor,(o(e)&&(e===u||r(e.prototype))||i(e)&&null===(e=e[a]))&&(e=void 0)),void 0===e?u:e}},88627:(t,e,n)=>{var r=n(98531);t.exports=function(t,e){return new(r(t))(0===e?0:e)}},33809:(t,e,n)=>{var r=n(90649),o=n(78309);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){o(t,"throw",e)}}},25542:(t,e,n)=>{var r=n(39189)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[r]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var n=!1;try{var i={};i[r]=function(){return{next:function(){return{done:n=!0}}}},t(i)}catch(t){}return n}},17170:(t,e,n)=>{var r=n(38982),o=r({}.toString),i=r("".slice);t.exports=function(t){return i(o(t),8,-1)}},75493:(t,e,n)=>{var r=n(13878),o=n(11055),i=n(17170),a=n(39189)("toStringTag"),u=Object,c="Arguments"==i(function(){return arguments}());t.exports=r?i:function(t){var e,n,r;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=u(t),a))?n:c?i(e):"Object"==(r=i(e))&&o(e.callee)?"Arguments":r}},49720:(t,e,n)=>{"use strict";var r=n(32814),o=n(61548),i=n(14101),a=n(67302),u=n(37809),c=n(40899),s=n(4846),l=n(49626),f=n(42579),p=n(18807),d=n(4426),h=n(89277).fastKey,y=n(58319),v=y.set,m=y.getterFor;t.exports={getConstructor:function(t,e,n,l){var f=t((function(t,o){u(t,p),v(t,{type:e,index:r(null),first:void 0,last:void 0,size:0}),d||(t.size=0),c(o)||s(o,t[l],{that:t,AS_ENTRIES:n})})),p=f.prototype,y=m(e),g=function(t,e,n){var r,o,i=y(t),a=b(t,e);return a?a.value=n:(i.last=a={index:o=h(e,!0),key:e,value:n,previous:r=i.last,next:void 0,removed:!1},i.first||(i.first=a),r&&(r.next=a),d?i.size++:t.size++,"F"!==o&&(i.index[o]=a)),t},b=function(t,e){var n,r=y(t),o=h(e);if("F"!==o)return r.index[o];for(n=r.first;n;n=n.next)if(n.key==e)return n};return i(p,{clear:function(){for(var t=y(this),e=t.index,n=t.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete e[n.index],n=n.next;t.first=t.last=void 0,d?t.size=0:this.size=0},delete:function(t){var e=this,n=y(e),r=b(e,t);if(r){var o=r.next,i=r.previous;delete n.index[r.index],r.removed=!0,i&&(i.next=o),o&&(o.previous=i),n.first==r&&(n.first=o),n.last==r&&(n.last=i),d?n.size--:e.size--}return!!r},forEach:function(t){for(var e,n=y(this),r=a(t,arguments.length>1?arguments[1]:void 0);e=e?e.next:n.first;)for(r(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!b(this,t)}}),i(p,n?{get:function(t){var e=b(this,t);return e&&e.value},set:function(t,e){return g(this,0===t?0:t,e)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),d&&o(p,"size",{configurable:!0,get:function(){return y(this).size}}),f},setStrong:function(t,e,n){var r=e+" Iterator",o=m(e),i=m(r);l(t,e,(function(t,e){v(this,{type:r,target:t,state:o(t),kind:e,last:void 0})}),(function(){for(var t=i(this),e=t.kind,n=t.last;n&&n.removed;)n=n.previous;return t.target&&(t.last=n=n?n.next:t.state.first)?f("keys"==e?n.key:"values"==e?n.value:[n.key,n.value],!1):(t.target=void 0,f(void 0,!0))}),n?"entries":"values",!n,!0),p(e)}}},42715:(t,e,n)=>{"use strict";var r=n(38982),o=n(14101),i=n(89277).getWeakData,a=n(37809),u=n(90649),c=n(40899),s=n(96692),l=n(4846),f=n(31567),p=n(34863),d=n(58319),h=d.set,y=d.getterFor,v=f.find,m=f.findIndex,g=r([].splice),b=0,_=function(t){return t.frozen||(t.frozen=new w)},w=function(){this.entries=[]},S=function(t,e){return v(t.entries,(function(t){return t[0]===e}))};w.prototype={get:function(t){var e=S(this,t);if(e)return e[1]},has:function(t){return!!S(this,t)},set:function(t,e){var n=S(this,t);n?n[1]=e:this.entries.push([t,e])},delete:function(t){var e=m(this.entries,(function(e){return e[0]===t}));return~e&&g(this.entries,e,1),!!~e}},t.exports={getConstructor:function(t,e,n,r){var f=t((function(t,o){a(t,d),h(t,{type:e,id:b++,frozen:void 0}),c(o)||l(o,t[r],{that:t,AS_ENTRIES:n})})),d=f.prototype,v=y(e),m=function(t,e,n){var r=v(t),o=i(u(e),!0);return!0===o?_(r).set(e,n):o[r.id]=n,t};return o(d,{delete:function(t){var e=v(this);if(!s(t))return!1;var n=i(t);return!0===n?_(e).delete(t):n&&p(n,e.id)&&delete n[e.id]},has:function(t){var e=v(this);if(!s(t))return!1;var n=i(t);return!0===n?_(e).has(t):n&&p(n,e.id)}}),o(d,n?{get:function(t){var e=v(this);if(s(t)){var n=i(t);return!0===n?_(e).get(t):n?n[e.id]:void 0}},set:function(t,e){return m(this,t,e)}}:{add:function(t){return m(this,t,!0)}}),f}}},35365:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(38982),a=n(96942),u=n(92446),c=n(89277),s=n(4846),l=n(37809),f=n(11055),p=n(40899),d=n(96692),h=n(79061),y=n(25542),v=n(49233),m=n(86953);t.exports=function(t,e,n){var g=-1!==t.indexOf("Map"),b=-1!==t.indexOf("Weak"),_=g?"set":"add",w=o[t],S=w&&w.prototype,C=w,E={},I=function(t){var e=i(S[t]);u(S,t,"add"==t?function(t){return e(this,0===t?0:t),this}:"delete"==t?function(t){return!(b&&!d(t))&&e(this,0===t?0:t)}:"get"==t?function(t){return b&&!d(t)?void 0:e(this,0===t?0:t)}:"has"==t?function(t){return!(b&&!d(t))&&e(this,0===t?0:t)}:function(t,n){return e(this,0===t?0:t,n),this})};if(a(t,!f(w)||!(b||S.forEach&&!h((function(){(new w).entries().next()})))))C=n.getConstructor(e,t,g,_),c.enable();else if(a(t,!0)){var O=new C,P=O[_](b?{}:-0,1)!=O,T=h((function(){O.has(1)})),A=y((function(t){new w(t)})),x=!b&&h((function(){for(var t=new w,e=5;e--;)t[_](e,e);return!t.has(-0)}));A||((C=e((function(t,e){l(t,S);var n=m(new w,t,C);return p(e)||s(e,n[_],{that:n,AS_ENTRIES:g}),n}))).prototype=S,S.constructor=C),(T||x)&&(I("delete"),I("has"),g&&I("get")),(x||P)&&I(_),b&&S.clear&&delete S.clear}return E[t]=C,r({global:!0,constructor:!0,forced:C!=w},E),v(C,t),b||n.setStrong(C,t,g),C}},14938:(t,e,n)=>{var r=n(34863),o=n(8517),i=n(77637),a=n(59143);t.exports=function(t,e,n){for(var u=o(e),c=a.f,s=i.f,l=0;l{var r=n(39189)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,"/./"[t](e)}catch(t){}}return!1}},16797:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},68662:(t,e,n)=>{var r=n(38982),o=n(29412),i=n(96641),a=/"/g,u=r("".replace);t.exports=function(t,e,n,r){var c=i(o(t)),s="<"+e;return""!==n&&(s+=" "+n+'="'+u(i(r),a,""")+'"'),s+">"+c+""}},42579:t=>{t.exports=function(t,e){return{value:t,done:e}}},69193:(t,e,n)=>{var r=n(4426),o=n(59143),i=n(52302);t.exports=r?function(t,e,n){return o.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},52302:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},25762:(t,e,n)=>{"use strict";var r=n(50243),o=n(59143),i=n(52302);t.exports=function(t,e,n){var a=r(e);a in t?o.f(t,a,i(0,n)):t[a]=n}},55362:(t,e,n)=>{"use strict";var r=n(90649),o=n(2272),i=TypeError;t.exports=function(t){if(r(this),"string"===t||"default"===t)t="string";else if("number"!==t)throw i("Incorrect hint");return o(this,t)}},61548:(t,e,n)=>{var r=n(58245),o=n(59143);t.exports=function(t,e,n){return n.get&&r(n.get,e,{getter:!0}),n.set&&r(n.set,e,{setter:!0}),o.f(t,e,n)}},92446:(t,e,n)=>{var r=n(11055),o=n(59143),i=n(58245),a=n(11891);t.exports=function(t,e,n,u){u||(u={});var c=u.enumerable,s=void 0!==u.name?u.name:e;if(r(n)&&i(n,s,u),u.global)c?t[e]=n:a(e,n);else{try{u.unsafe?t[e]&&(c=!0):delete t[e]}catch(t){}c?t[e]=n:o.f(t,e,{value:n,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return t}},14101:(t,e,n)=>{var r=n(92446);t.exports=function(t,e,n){for(var o in e)r(t,o,e[o],n);return t}},11891:(t,e,n)=>{var r=n(21833),o=Object.defineProperty;t.exports=function(t,e){try{o(r,t,{value:e,configurable:!0,writable:!0})}catch(n){r[t]=e}return e}},87472:(t,e,n)=>{"use strict";var r=n(79269),o=TypeError;t.exports=function(t,e){if(!delete t[e])throw o("Cannot delete property "+r(e)+" of "+r(t))}},4426:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},36185:t=>{var e="object"==typeof document&&document.all,n=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:n}},46349:(t,e,n)=>{var r=n(21833),o=n(96692),i=r.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},68655:t=>{var e=TypeError;t.exports=function(t){if(t>9007199254740991)throw e("Maximum allowed index exceeded");return t}},4774:t=>{t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},4474:(t,e,n)=>{var r=n(46349)("span").classList,o=r&&r.constructor&&r.constructor.prototype;t.exports=o===Object.prototype?void 0:o},27496:(t,e,n)=>{var r=n(60514).match(/firefox\/(\d+)/i);t.exports=!!r&&+r[1]},43704:(t,e,n)=>{var r=n(99574),o=n(36954);t.exports=!r&&!o&&"object"==typeof window&&"object"==typeof document},99574:t=>{t.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},36928:(t,e,n)=>{var r=n(60514);t.exports=/MSIE|Trident/.test(r)},52134:(t,e,n)=>{var r=n(60514);t.exports=/ipad|iphone|ipod/i.test(r)&&"undefined"!=typeof Pebble},19997:(t,e,n)=>{var r=n(60514);t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(r)},36954:(t,e,n)=>{var r=n(17170);t.exports="undefined"!=typeof process&&"process"==r(process)},89299:(t,e,n)=>{var r=n(60514);t.exports=/web0s(?!.*chrome)/i.test(r)},60514:t=>{t.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},36918:(t,e,n)=>{var r,o,i=n(21833),a=n(60514),u=i.process,c=i.Deno,s=u&&u.versions||c&&c.version,l=s&&s.v8;l&&(o=(r=l.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!o&&a&&(!(r=a.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=a.match(/Chrome\/(\d+)/))&&(o=+r[1]),t.exports=o},53522:(t,e,n)=>{var r=n(60514).match(/AppleWebKit\/(\d+)\./);t.exports=!!r&&+r[1]},39513:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},58288:(t,e,n)=>{var r=n(21833),o=n(77637).f,i=n(69193),a=n(92446),u=n(11891),c=n(14938),s=n(96942);t.exports=function(t,e){var n,l,f,p,d,h=t.target,y=t.global,v=t.stat;if(n=y?r:v?r[h]||u(h,{}):(r[h]||{}).prototype)for(l in e){if(p=e[l],f=t.dontCallGetSet?(d=o(n,l))&&d.value:n[l],!s(y?l:h+(v?".":"#")+l,t.forced)&&void 0!==f){if(typeof p==typeof f)continue;c(p,f)}(t.sham||f&&f.sham)&&i(p,"sham",!0),a(n,l,p,t)}}},79061:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},35146:(t,e,n)=>{"use strict";n(18489);var r=n(46526),o=n(92446),i=n(74989),a=n(79061),u=n(39189),c=n(69193),s=u("species"),l=RegExp.prototype;t.exports=function(t,e,n,f){var p=u(t),d=!a((function(){var e={};return e[p]=function(){return 7},7!=""[t](e)})),h=d&&!a((function(){var e=!1,n=/a/;return"split"===t&&((n={}).constructor={},n.constructor[s]=function(){return n},n.flags="",n[p]=/./[p]),n.exec=function(){return e=!0,null},n[p](""),!e}));if(!d||!h||n){var y=r(/./[p]),v=e(p,""[t],(function(t,e,n,o,a){var u=r(t),c=e.exec;return c===i||c===l.exec?d&&!a?{done:!0,value:y(e,n,o)}:{done:!0,value:u(n,e,o)}:{done:!1}}));o(String.prototype,t,v[0]),o(l,p,v[1])}f&&c(l[p],"sham",!0)}},96493:(t,e,n)=>{"use strict";var r=n(57886),o=n(12244),i=n(68655),a=n(67302),u=function(t,e,n,c,s,l,f,p){for(var d,h,y=s,v=0,m=!!f&&a(f,p);v0&&r(d)?(h=o(d),y=u(t,e,d,h,y,l-1)-1):(i(y+1),t[y]=d),y++),v++;return y};t.exports=u},1566:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},33247:(t,e,n)=>{var r=n(8470),o=Function.prototype,i=o.apply,a=o.call;t.exports="object"==typeof Reflect&&Reflect.apply||(r?a.bind(i):function(){return a.apply(i,arguments)})},67302:(t,e,n)=>{var r=n(46526),o=n(35476),i=n(8470),a=r(r.bind);t.exports=function(t,e){return o(t),void 0===e?t:i?a(t,e):function(){return t.apply(e,arguments)}}},8470:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},44931:(t,e,n)=>{var r=n(8470),o=Function.prototype.call;t.exports=r?o.bind(o):function(){return o.apply(o,arguments)}},92684:(t,e,n)=>{var r=n(4426),o=n(34863),i=Function.prototype,a=r&&Object.getOwnPropertyDescriptor,u=o(i,"name"),c=u&&"something"===function(){}.name,s=u&&(!r||r&&a(i,"name").configurable);t.exports={EXISTS:u,PROPER:c,CONFIGURABLE:s}},67652:(t,e,n)=>{var r=n(38982),o=n(35476);t.exports=function(t,e,n){try{return r(o(Object.getOwnPropertyDescriptor(t,e)[n]))}catch(t){}}},46526:(t,e,n)=>{var r=n(17170),o=n(38982);t.exports=function(t){if("Function"===r(t))return o(t)}},38982:(t,e,n)=>{var r=n(8470),o=Function.prototype,i=o.call,a=r&&o.bind.bind(i,i);t.exports=r?a:function(t){return function(){return i.apply(t,arguments)}}},78797:(t,e,n)=>{var r=n(21833),o=n(11055);t.exports=function(t,e){return arguments.length<2?(n=r[t],o(n)?n:void 0):r[t]&&r[t][e];var n}},16421:(t,e,n)=>{var r=n(75493),o=n(4224),i=n(40899),a=n(45347),u=n(39189)("iterator");t.exports=function(t){if(!i(t))return o(t,u)||o(t,"@@iterator")||a[r(t)]}},81963:(t,e,n)=>{var r=n(44931),o=n(35476),i=n(90649),a=n(79269),u=n(16421),c=TypeError;t.exports=function(t,e){var n=arguments.length<2?u(t):e;if(o(n))return i(r(n,t));throw c(a(t)+" is not iterable")}},54875:(t,e,n)=>{var r=n(38982),o=n(57886),i=n(11055),a=n(17170),u=n(96641),c=r([].push);t.exports=function(t){if(i(t))return t;if(o(t)){for(var e=t.length,n=[],r=0;r{var r=n(35476),o=n(40899);t.exports=function(t,e){var n=t[e];return o(n)?void 0:r(n)}},34032:(t,e,n)=>{var r=n(38982),o=n(50775),i=Math.floor,a=r("".charAt),u=r("".replace),c=r("".slice),s=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,l=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,n,r,f,p){var d=n+t.length,h=r.length,y=l;return void 0!==f&&(f=o(f),y=s),u(p,y,(function(o,u){var s;switch(a(u,0)){case"$":return"$";case"&":return t;case"`":return c(e,0,n);case"'":return c(e,d);case"<":s=f[c(u,1,-1)];break;default:var l=+u;if(0===l)return o;if(l>h){var p=i(l/10);return 0===p?o:p<=h?void 0===r[p-1]?a(u,1):r[p-1]+a(u,1):o}s=r[l-1]}return void 0===s?"":s}))}},21833:function(t,e,n){var r=function(t){return t&&t.Math==Math&&t};t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n.g&&n.g)||function(){return this}()||this||Function("return this")()},34863:(t,e,n)=>{var r=n(38982),o=n(50775),i=r({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return i(o(t),e)}},43343:t=>{t.exports={}},69991:t=>{t.exports=function(t,e){try{1==arguments.length?console.error(t):console.error(t,e)}catch(t){}}},75527:(t,e,n)=>{var r=n(78797);t.exports=r("document","documentElement")},99667:(t,e,n)=>{var r=n(4426),o=n(79061),i=n(46349);t.exports=!r&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},13228:t=>{var e=Array,n=Math.abs,r=Math.pow,o=Math.floor,i=Math.log,a=Math.LN2;t.exports={pack:function(t,u,c){var s,l,f,p=e(c),d=8*c-u-1,h=(1<>1,v=23===u?r(2,-24)-r(2,-77):0,m=t<0||0===t&&1/t<0?1:0,g=0;for((t=n(t))!=t||t===1/0?(l=t!=t?1:0,s=h):(s=o(i(t)/a),t*(f=r(2,-s))<1&&(s--,f*=2),(t+=s+y>=1?v/f:v*r(2,1-y))*f>=2&&(s++,f/=2),s+y>=h?(l=0,s=h):s+y>=1?(l=(t*f-1)*r(2,u),s+=y):(l=t*r(2,y-1)*r(2,u),s=0));u>=8;)p[g++]=255&l,l/=256,u-=8;for(s=s<0;)p[g++]=255&s,s/=256,d-=8;return p[--g]|=128*m,p},unpack:function(t,e){var n,o=t.length,i=8*o-e-1,a=(1<>1,c=i-7,s=o-1,l=t[s--],f=127&l;for(l>>=7;c>0;)f=256*f+t[s--],c-=8;for(n=f&(1<<-c)-1,f>>=-c,c+=e;c>0;)n=256*n+t[s--],c-=8;if(0===f)f=1-u;else{if(f===a)return n?NaN:l?-1/0:1/0;n+=r(2,e),f-=u}return(l?-1:1)*n*r(2,f-e)}}},7461:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(17170),a=Object,u=r("".split);t.exports=o((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==i(t)?u(t,""):a(t)}:a},86953:(t,e,n)=>{var r=n(11055),o=n(96692),i=n(26213);t.exports=function(t,e,n){var a,u;return i&&r(a=e.constructor)&&a!==n&&o(u=a.prototype)&&u!==n.prototype&&i(t,u),t}},27728:(t,e,n)=>{var r=n(38982),o=n(11055),i=n(47099),a=r(Function.toString);o(i.inspectSource)||(i.inspectSource=function(t){return a(t)}),t.exports=i.inspectSource},89277:(t,e,n)=>{var r=n(58288),o=n(38982),i=n(43343),a=n(96692),u=n(34863),c=n(59143).f,s=n(47210),l=n(83744),f=n(81278),p=n(64550),d=n(1566),h=!1,y=p("meta"),v=0,m=function(t){c(t,y,{value:{objectID:"O"+v++,weakData:{}}})},g=t.exports={enable:function(){g.enable=function(){},h=!0;var t=s.f,e=o([].splice),n={};n[y]=1,t(n).length&&(s.f=function(n){for(var r=t(n),o=0,i=r.length;o{var r,o,i,a=n(74528),u=n(21833),c=n(96692),s=n(69193),l=n(34863),f=n(47099),p=n(40693),d=n(43343),h="Object already initialized",y=u.TypeError,v=u.WeakMap;if(a||f.state){var m=f.state||(f.state=new v);m.get=m.get,m.has=m.has,m.set=m.set,r=function(t,e){if(m.has(t))throw y(h);return e.facade=t,m.set(t,e),e},o=function(t){return m.get(t)||{}},i=function(t){return m.has(t)}}else{var g=p("state");d[g]=!0,r=function(t,e){if(l(t,g))throw y(h);return e.facade=t,s(t,g,e),e},o=function(t){return l(t,g)?t[g]:{}},i=function(t){return l(t,g)}}t.exports={set:r,get:o,has:i,enforce:function(t){return i(t)?o(t):r(t,{})},getterFor:function(t){return function(e){var n;if(!c(e)||(n=o(e)).type!==t)throw y("Incompatible receiver, "+t+" required");return n}}}},77847:(t,e,n)=>{var r=n(39189),o=n(45347),i=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},57886:(t,e,n)=>{var r=n(17170);t.exports=Array.isArray||function(t){return"Array"==r(t)}},11055:(t,e,n)=>{var r=n(36185),o=r.all;t.exports=r.IS_HTMLDDA?function(t){return"function"==typeof t||t===o}:function(t){return"function"==typeof t}},11547:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(11055),a=n(75493),u=n(78797),c=n(27728),s=function(){},l=[],f=u("Reflect","construct"),p=/^\s*(?:class|function)\b/,d=r(p.exec),h=!p.exec(s),y=function(t){if(!i(t))return!1;try{return f(s,l,t),!0}catch(t){return!1}},v=function(t){if(!i(t))return!1;switch(a(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!d(p,c(t))}catch(t){return!0}};v.sham=!0,t.exports=!f||o((function(){var t;return y(y.call)||!y(Object)||!y((function(){t=!0}))||t}))?v:y},96942:(t,e,n)=>{var r=n(79061),o=n(11055),i=/#|\.prototype\./,a=function(t,e){var n=c[u(t)];return n==l||n!=s&&(o(e)?r(e):!!e)},u=a.normalize=function(t){return String(t).replace(i,".").toLowerCase()},c=a.data={},s=a.NATIVE="N",l=a.POLYFILL="P";t.exports=a},40899:t=>{t.exports=function(t){return null==t}},96692:(t,e,n)=>{var r=n(11055),o=n(36185),i=o.all;t.exports=o.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:r(t)||t===i}:function(t){return"object"==typeof t?null!==t:r(t)}},59785:t=>{t.exports=!1},16030:(t,e,n)=>{var r=n(96692),o=n(17170),i=n(39189)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[i])?!!e:"RegExp"==o(t))}},30907:(t,e,n)=>{var r=n(78797),o=n(11055),i=n(47931),a=n(92010),u=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=r("Symbol");return o(e)&&i(e.prototype,u(t))}},4846:(t,e,n)=>{var r=n(67302),o=n(44931),i=n(90649),a=n(79269),u=n(77847),c=n(12244),s=n(47931),l=n(81963),f=n(16421),p=n(78309),d=TypeError,h=function(t,e){this.stopped=t,this.result=e},y=h.prototype;t.exports=function(t,e,n){var v,m,g,b,_,w,S,C=n&&n.that,E=!(!n||!n.AS_ENTRIES),I=!(!n||!n.IS_RECORD),O=!(!n||!n.IS_ITERATOR),P=!(!n||!n.INTERRUPTED),T=r(e,C),A=function(t){return v&&p(v,"normal",t),new h(!0,t)},x=function(t){return E?(i(t),P?T(t[0],t[1],A):T(t[0],t[1])):P?T(t,A):T(t)};if(I)v=t.iterator;else if(O)v=t;else{if(!(m=f(t)))throw d(a(t)+" is not iterable");if(u(m)){for(g=0,b=c(t);b>g;g++)if((_=x(t[g]))&&s(y,_))return _;return new h(!1)}v=l(t,m)}for(w=I?t.next:v.next;!(S=o(w,v)).done;){try{_=x(S.value)}catch(t){p(v,"throw",t)}if("object"==typeof _&&_&&s(y,_))return _}return new h(!1)}},78309:(t,e,n)=>{var r=n(44931),o=n(90649),i=n(4224);t.exports=function(t,e,n){var a,u;o(t);try{if(!(a=i(t,"return"))){if("throw"===e)throw n;return n}a=r(a,t)}catch(t){u=!0,a=t}if("throw"===e)throw n;if(u)throw a;return o(a),n}},75700:(t,e,n)=>{"use strict";var r=n(26679).IteratorPrototype,o=n(32814),i=n(52302),a=n(49233),u=n(45347),c=function(){return this};t.exports=function(t,e,n,s){var l=e+" Iterator";return t.prototype=o(r,{next:i(+!s,n)}),a(t,l,!1,!0),u[l]=c,t}},49626:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(59785),a=n(92684),u=n(11055),c=n(75700),s=n(52473),l=n(26213),f=n(49233),p=n(69193),d=n(92446),h=n(39189),y=n(45347),v=n(26679),m=a.PROPER,g=a.CONFIGURABLE,b=v.IteratorPrototype,_=v.BUGGY_SAFARI_ITERATORS,w=h("iterator"),S="keys",C="values",E="entries",I=function(){return this};t.exports=function(t,e,n,a,h,v,O){c(n,e,a);var P,T,A,x=function(t){if(t===h&&N)return N;if(!_&&t in M)return M[t];switch(t){case S:case C:case E:return function(){return new n(this,t)}}return function(){return new n(this)}},k=e+" Iterator",R=!1,M=t.prototype,j=M[w]||M["@@iterator"]||h&&M[h],N=!_&&j||x(h),D="Array"==e&&M.entries||j;if(D&&(P=s(D.call(new t)))!==Object.prototype&&P.next&&(i||s(P)===b||(l?l(P,b):u(P[w])||d(P,w,I)),f(P,k,!0,!0),i&&(y[k]=I)),m&&h==C&&j&&j.name!==C&&(!i&&g?p(M,"name",C):(R=!0,N=function(){return o(j,this)})),h)if(T={values:x(C),keys:v?N:x(S),entries:x(E)},O)for(A in T)(_||R||!(A in M))&&d(M,A,T[A]);else r({target:e,proto:!0,forced:_||R},T);return i&&!O||M[w]===N||d(M,w,N,{name:h}),y[e]=N,T}},26679:(t,e,n)=>{"use strict";var r,o,i,a=n(79061),u=n(11055),c=n(96692),s=n(32814),l=n(52473),f=n(92446),p=n(39189),d=n(59785),h=p("iterator"),y=!1;[].keys&&("next"in(i=[].keys())?(o=l(l(i)))!==Object.prototype&&(r=o):y=!0),!c(r)||a((function(){var t={};return r[h].call(t)!==t}))?r={}:d&&(r=s(r)),u(r[h])||f(r,h,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:y}},45347:t=>{t.exports={}},12244:(t,e,n)=>{var r=n(99536);t.exports=function(t){return r(t.length)}},58245:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(11055),a=n(34863),u=n(4426),c=n(92684).CONFIGURABLE,s=n(27728),l=n(58319),f=l.enforce,p=l.get,d=String,h=Object.defineProperty,y=r("".slice),v=r("".replace),m=r([].join),g=u&&!o((function(){return 8!==h((function(){}),"length",{value:8}).length})),b=String(String).split("String"),_=t.exports=function(t,e,n){"Symbol("===y(d(e),0,7)&&(e="["+v(d(e),/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!a(t,"name")||c&&t.name!==e)&&(u?h(t,"name",{value:e,configurable:!0}):t.name=e),g&&n&&a(n,"arity")&&t.length!==n.arity&&h(t,"length",{value:n.arity});try{n&&a(n,"constructor")&&n.constructor?u&&h(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var r=f(t);return a(r,"source")||(r.source=m(b,"string"==typeof e?e:"")),t};Function.prototype.toString=_((function(){return i(this)&&p(this).source||s(this)}),"toString")},56811:t=>{var e=Math.ceil,n=Math.floor;t.exports=Math.trunc||function(t){var r=+t;return(r>0?n:e)(r)}},26269:(t,e,n)=>{var r,o,i,a,u,c=n(21833),s=n(67302),l=n(77637).f,f=n(21627).set,p=n(72879),d=n(19997),h=n(52134),y=n(89299),v=n(36954),m=c.MutationObserver||c.WebKitMutationObserver,g=c.document,b=c.process,_=c.Promise,w=l(c,"queueMicrotask"),S=w&&w.value;if(!S){var C=new p,E=function(){var t,e;for(v&&(t=b.domain)&&t.exit();e=C.get();)try{e()}catch(t){throw C.head&&r(),t}t&&t.enter()};d||v||y||!m||!g?!h&&_&&_.resolve?((a=_.resolve(void 0)).constructor=_,u=s(a.then,a),r=function(){u(E)}):v?r=function(){b.nextTick(E)}:(f=s(f,c),r=function(){f(E)}):(o=!0,i=g.createTextNode(""),new m(E).observe(i,{characterData:!0}),r=function(){i.data=o=!o}),S=function(t){C.head||r(),C.add(t)}}t.exports=S},76185:(t,e,n)=>{"use strict";var r=n(35476),o=TypeError,i=function(t){var e,n;this.promise=new t((function(t,r){if(void 0!==e||void 0!==n)throw o("Bad Promise constructor");e=t,n=r})),this.resolve=r(e),this.reject=r(n)};t.exports.f=function(t){return new i(t)}},15425:(t,e,n)=>{var r=n(16030),o=TypeError;t.exports=function(t){if(r(t))throw o("The method doesn't accept regular expressions");return t}},55870:(t,e,n)=>{var r=n(21833),o=n(79061),i=n(38982),a=n(96641),u=n(92572).trim,c=n(18986),s=i("".charAt),l=r.parseFloat,f=r.Symbol,p=f&&f.iterator,d=1/l(c+"-0")!=-1/0||p&&!o((function(){l(Object(p))}));t.exports=d?function(t){var e=u(a(t)),n=l(e);return 0===n&&"-"==s(e,0)?-0:n}:l},145:(t,e,n)=>{var r=n(21833),o=n(79061),i=n(38982),a=n(96641),u=n(92572).trim,c=n(18986),s=r.parseInt,l=r.Symbol,f=l&&l.iterator,p=/^[+-]?0x/i,d=i(p.exec),h=8!==s(c+"08")||22!==s(c+"0x16")||f&&!o((function(){s(Object(f))}));t.exports=h?function(t,e){var n=u(a(t));return s(n,e>>>0||(d(p,n)?16:10))}:s},58187:(t,e,n)=>{"use strict";var r=n(4426),o=n(38982),i=n(44931),a=n(79061),u=n(80094),c=n(68255),s=n(46391),l=n(50775),f=n(7461),p=Object.assign,d=Object.defineProperty,h=o([].concat);t.exports=!p||a((function(){if(r&&1!==p({b:1},p(d({},"a",{enumerable:!0,get:function(){d(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),o="abcdefghijklmnopqrst";return t[n]=7,o.split("").forEach((function(t){e[t]=t})),7!=p({},t)[n]||u(p({},e)).join("")!=o}))?function(t,e){for(var n=l(t),o=arguments.length,a=1,p=c.f,d=s.f;o>a;)for(var y,v=f(arguments[a++]),m=p?h(u(v),p(v)):u(v),g=m.length,b=0;g>b;)y=m[b++],r&&!i(d,v,y)||(n[y]=v[y]);return n}:p},32814:(t,e,n)=>{var r,o=n(90649),i=n(2459),a=n(39513),u=n(43343),c=n(75527),s=n(46349),l=n(40693),f="prototype",p="script",d=l("IE_PROTO"),h=function(){},y=function(t){return"<"+p+">"+t+""},v=function(t){t.write(y("")),t.close();var e=t.parentWindow.Object;return t=null,e},m=function(){try{r=new ActiveXObject("htmlfile")}catch(t){}var t,e,n;m="undefined"!=typeof document?document.domain&&r?v(r):(e=s("iframe"),n="java"+p+":",e.style.display="none",c.appendChild(e),e.src=String(n),(t=e.contentWindow.document).open(),t.write(y("document.F=Object")),t.close(),t.F):v(r);for(var o=a.length;o--;)delete m[f][a[o]];return m()};u[d]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(h[f]=o(t),n=new h,h[f]=null,n[d]=t):n=m(),void 0===e?n:i.f(n,e)}},2459:(t,e,n)=>{var r=n(4426),o=n(75828),i=n(59143),a=n(90649),u=n(4395),c=n(80094);e.f=r&&!o?Object.defineProperties:function(t,e){a(t);for(var n,r=u(e),o=c(e),s=o.length,l=0;s>l;)i.f(t,n=o[l++],r[n]);return t}},59143:(t,e,n)=>{var r=n(4426),o=n(99667),i=n(75828),a=n(90649),u=n(50243),c=TypeError,s=Object.defineProperty,l=Object.getOwnPropertyDescriptor,f="enumerable",p="configurable",d="writable";e.f=r?i?function(t,e,n){if(a(t),e=u(e),a(n),"function"==typeof t&&"prototype"===e&&"value"in n&&d in n&&!n[d]){var r=l(t,e);r&&r[d]&&(t[e]=n.value,n={configurable:p in n?n[p]:r[p],enumerable:f in n?n[f]:r[f],writable:!1})}return s(t,e,n)}:s:function(t,e,n){if(a(t),e=u(e),a(n),o)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw c("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},77637:(t,e,n)=>{var r=n(4426),o=n(44931),i=n(46391),a=n(52302),u=n(4395),c=n(50243),s=n(34863),l=n(99667),f=Object.getOwnPropertyDescriptor;e.f=r?f:function(t,e){if(t=u(t),e=c(e),l)try{return f(t,e)}catch(t){}if(s(t,e))return a(!o(i.f,t,e),t[e])}},83744:(t,e,n)=>{var r=n(17170),o=n(4395),i=n(47210).f,a=n(10301),u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"Window"==r(t)?function(t){try{return i(t)}catch(t){return a(u)}}(t):i(o(t))}},47210:(t,e,n)=>{var r=n(4114),o=n(39513).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,o)}},68255:(t,e)=>{e.f=Object.getOwnPropertySymbols},52473:(t,e,n)=>{var r=n(34863),o=n(11055),i=n(50775),a=n(40693),u=n(16797),c=a("IE_PROTO"),s=Object,l=s.prototype;t.exports=u?s.getPrototypeOf:function(t){var e=i(t);if(r(e,c))return e[c];var n=e.constructor;return o(n)&&e instanceof n?n.prototype:e instanceof s?l:null}},81278:(t,e,n)=>{var r=n(79061),o=n(96692),i=n(17170),a=n(65642),u=Object.isExtensible,c=r((function(){u(1)}));t.exports=c||a?function(t){return!!o(t)&&(!a||"ArrayBuffer"!=i(t))&&(!u||u(t))}:u},47931:(t,e,n)=>{var r=n(38982);t.exports=r({}.isPrototypeOf)},4114:(t,e,n)=>{var r=n(38982),o=n(34863),i=n(4395),a=n(20895).indexOf,u=n(43343),c=r([].push);t.exports=function(t,e){var n,r=i(t),s=0,l=[];for(n in r)!o(u,n)&&o(r,n)&&c(l,n);for(;e.length>s;)o(r,n=e[s++])&&(~a(l,n)||c(l,n));return l}},80094:(t,e,n)=>{var r=n(4114),o=n(39513);t.exports=Object.keys||function(t){return r(t,o)}},46391:(t,e)=>{"use strict";var n={}.propertyIsEnumerable,r=Object.getOwnPropertyDescriptor,o=r&&!n.call({1:2},1);e.f=o?function(t){var e=r(this,t);return!!e&&e.enumerable}:n},26213:(t,e,n)=>{var r=n(67652),o=n(90649),i=n(1520);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,n={};try{(t=r(Object.prototype,"__proto__","set"))(n,[]),e=n instanceof Array}catch(t){}return function(n,r){return o(n),i(r),e?t(n,r):n.__proto__=r,n}}():void 0)},70671:(t,e,n)=>{var r=n(4426),o=n(79061),i=n(38982),a=n(52473),u=n(80094),c=n(4395),s=i(n(46391).f),l=i([].push),f=r&&o((function(){var t=Object.create(null);return t[2]=2,!s(t,2)})),p=function(t){return function(e){for(var n,o=c(e),i=u(o),p=f&&null===a(o),d=i.length,h=0,y=[];d>h;)n=i[h++],r&&!(p?n in o:s(o,n))||l(y,t?[n,o[n]]:o[n]);return y}};t.exports={entries:p(!0),values:p(!1)}},42553:(t,e,n)=>{"use strict";var r=n(13878),o=n(75493);t.exports=r?{}.toString:function(){return"[object "+o(this)+"]"}},2272:(t,e,n)=>{var r=n(44931),o=n(11055),i=n(96692),a=TypeError;t.exports=function(t,e){var n,u;if("string"===e&&o(n=t.toString)&&!i(u=r(n,t)))return u;if(o(n=t.valueOf)&&!i(u=r(n,t)))return u;if("string"!==e&&o(n=t.toString)&&!i(u=r(n,t)))return u;throw a("Can't convert object to primitive value")}},8517:(t,e,n)=>{var r=n(78797),o=n(38982),i=n(47210),a=n(68255),u=n(90649),c=o([].concat);t.exports=r("Reflect","ownKeys")||function(t){var e=i.f(u(t)),n=a.f;return n?c(e,n(t)):e}},16665:(t,e,n)=>{var r=n(21833);t.exports=r},63341:t=>{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},43322:(t,e,n)=>{var r=n(21833),o=n(70828),i=n(11055),a=n(96942),u=n(27728),c=n(39189),s=n(43704),l=n(99574),f=n(59785),p=n(36918),d=o&&o.prototype,h=c("species"),y=!1,v=i(r.PromiseRejectionEvent),m=a("Promise",(function(){var t=u(o),e=t!==String(o);if(!e&&66===p)return!0;if(f&&(!d.catch||!d.finally))return!0;if(!p||p<51||!/native code/.test(t)){var n=new o((function(t){t(1)})),r=function(t){t((function(){}),(function(){}))};if((n.constructor={})[h]=r,!(y=n.then((function(){}))instanceof r))return!0}return!e&&(s||l)&&!v}));t.exports={CONSTRUCTOR:m,REJECTION_EVENT:v,SUBCLASSING:y}},70828:(t,e,n)=>{var r=n(21833);t.exports=r.Promise},77472:(t,e,n)=>{var r=n(90649),o=n(96692),i=n(76185);t.exports=function(t,e){if(r(t),o(e)&&e.constructor===t)return e;var n=i.f(t);return(0,n.resolve)(e),n.promise}},32291:(t,e,n)=>{var r=n(70828),o=n(25542),i=n(43322).CONSTRUCTOR;t.exports=i||!o((function(t){r.all(t).then(void 0,(function(){}))}))},76434:(t,e,n)=>{var r=n(59143).f;t.exports=function(t,e,n){n in t||r(t,n,{configurable:!0,get:function(){return e[n]},set:function(t){e[n]=t}})}},72879:t=>{var e=function(){this.head=null,this.tail=null};e.prototype={add:function(t){var e={item:t,next:null},n=this.tail;n?n.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return null===(this.head=t.next)&&(this.tail=null),t.item}},t.exports=e},47160:(t,e,n)=>{var r=n(44931),o=n(90649),i=n(11055),a=n(17170),u=n(74989),c=TypeError;t.exports=function(t,e){var n=t.exec;if(i(n)){var s=r(n,t,e);return null!==s&&o(s),s}if("RegExp"===a(t))return r(u,t,e);throw c("RegExp#exec called on incompatible receiver")}},74989:(t,e,n)=>{"use strict";var r,o,i=n(44931),a=n(38982),u=n(96641),c=n(1881),s=n(60303),l=n(51435),f=n(32814),p=n(58319).get,d=n(99121),h=n(90324),y=l("native-string-replace",String.prototype.replace),v=RegExp.prototype.exec,m=v,g=a("".charAt),b=a("".indexOf),_=a("".replace),w=a("".slice),S=(o=/b*/g,i(v,r=/a/,"a"),i(v,o,"a"),0!==r.lastIndex||0!==o.lastIndex),C=s.BROKEN_CARET,E=void 0!==/()??/.exec("")[1];(S||E||C||d||h)&&(m=function(t){var e,n,r,o,a,s,l,d=this,h=p(d),I=u(t),O=h.raw;if(O)return O.lastIndex=d.lastIndex,e=i(m,O,I),d.lastIndex=O.lastIndex,e;var P=h.groups,T=C&&d.sticky,A=i(c,d),x=d.source,k=0,R=I;if(T&&(A=_(A,"y",""),-1===b(A,"g")&&(A+="g"),R=w(I,d.lastIndex),d.lastIndex>0&&(!d.multiline||d.multiline&&"\n"!==g(I,d.lastIndex-1))&&(x="(?: "+x+")",R=" "+R,k++),n=new RegExp("^(?:"+x+")",A)),E&&(n=new RegExp("^"+x+"$(?!\\s)",A)),S&&(r=d.lastIndex),o=i(v,T?n:d,R),T?o?(o.input=w(o.input,k),o[0]=w(o[0],k),o.index=d.lastIndex,d.lastIndex+=o[0].length):d.lastIndex=0:S&&o&&(d.lastIndex=d.global?o.index+o[0].length:r),E&&o&&o.length>1&&i(y,o[0],n,(function(){for(a=1;a{"use strict";var r=n(90649);t.exports=function(){var t=r(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},84228:(t,e,n)=>{var r=n(44931),o=n(34863),i=n(47931),a=n(1881),u=RegExp.prototype;t.exports=function(t){var e=t.flags;return void 0!==e||"flags"in u||o(t,"flags")||!i(u,t)?e:r(a,t)}},60303:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp,i=r((function(){var t=o("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),a=i||r((function(){return!o("a","y").sticky})),u=i||r((function(){var t=o("^r","gy");return t.lastIndex=2,null!=t.exec("str")}));t.exports={BROKEN_CARET:u,MISSED_STICKY:a,UNSUPPORTED_Y:i}},99121:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp;t.exports=r((function(){var t=o(".","s");return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)}))},90324:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp;t.exports=r((function(){var t=o("(?b)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$c")}))},29412:(t,e,n)=>{var r=n(40899),o=TypeError;t.exports=function(t){if(r(t))throw o("Can't call method on "+t);return t}},45448:t=>{t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},18807:(t,e,n)=>{"use strict";var r=n(78797),o=n(61548),i=n(39189),a=n(4426),u=i("species");t.exports=function(t){var e=r(t);a&&e&&!e[u]&&o(e,u,{configurable:!0,get:function(){return this}})}},49233:(t,e,n)=>{var r=n(59143).f,o=n(34863),i=n(39189)("toStringTag");t.exports=function(t,e,n){t&&!n&&(t=t.prototype),t&&!o(t,i)&&r(t,i,{configurable:!0,value:e})}},40693:(t,e,n)=>{var r=n(51435),o=n(64550),i=r("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},47099:(t,e,n)=>{var r=n(21833),o=n(11891),i="__core-js_shared__",a=r[i]||o(i,{});t.exports=a},51435:(t,e,n)=>{var r=n(59785),o=n(47099);(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.31.0",mode:r?"pure":"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})},46439:(t,e,n)=>{var r=n(90649),o=n(68634),i=n(40899),a=n(39189)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||i(n=r(u)[a])?e:o(n)}},15927:(t,e,n)=>{var r=n(79061);t.exports=function(t){return r((function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}))}},65877:(t,e,n)=>{var r=n(38982),o=n(91129),i=n(96641),a=n(29412),u=r("".charAt),c=r("".charCodeAt),s=r("".slice),l=function(t){return function(e,n){var r,l,f=i(a(e)),p=o(n),d=f.length;return p<0||p>=d?t?"":void 0:(r=c(f,p))<55296||r>56319||p+1===d||(l=c(f,p+1))<56320||l>57343?t?u(f,p):r:t?s(f,p,p+2):l-56320+(r-55296<<10)+65536}};t.exports={codeAt:l(!1),charAt:l(!0)}},96929:(t,e,n)=>{var r=n(60514);t.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(r)},8439:(t,e,n)=>{var r=n(38982),o=n(99536),i=n(96641),a=n(20471),u=n(29412),c=r(a),s=r("".slice),l=Math.ceil,f=function(t){return function(e,n,r){var a,f,p=i(u(e)),d=o(n),h=p.length,y=void 0===r?" ":i(r);return d<=h||""==y?p:((f=c(y,l((a=d-h)/y.length))).length>a&&(f=s(f,0,a)),t?p+f:f+p)}};t.exports={start:f(!1),end:f(!0)}},20471:(t,e,n)=>{"use strict";var r=n(91129),o=n(96641),i=n(29412),a=RangeError;t.exports=function(t){var e=o(i(this)),n="",u=r(t);if(u<0||u==1/0)throw a("Wrong number of repetitions");for(;u>0;(u>>>=1)&&(e+=e))1&u&&(n+=e);return n}},92024:(t,e,n)=>{"use strict";var r=n(92572).end,o=n(4160);t.exports=o("trimEnd")?function(){return r(this)}:"".trimEnd},4160:(t,e,n)=>{var r=n(92684).PROPER,o=n(79061),i=n(18986);t.exports=function(t){return o((function(){return!!i[t]()||"​…᠎"!=="​…᠎"[t]()||r&&i[t].name!==t}))}},10409:(t,e,n)=>{"use strict";var r=n(92572).start,o=n(4160);t.exports=o("trimStart")?function(){return r(this)}:"".trimStart},92572:(t,e,n)=>{var r=n(38982),o=n(29412),i=n(96641),a=n(18986),u=r("".replace),c=RegExp("^["+a+"]+"),s=RegExp("(^|[^"+a+"])["+a+"]+$"),l=function(t){return function(e){var n=i(o(e));return 1&t&&(n=u(n,c,"")),2&t&&(n=u(n,s,"$1")),n}};t.exports={start:l(1),end:l(2),trim:l(3)}},12289:(t,e,n)=>{var r=n(36918),o=n(79061),i=n(21833).String;t.exports=!!Object.getOwnPropertySymbols&&!o((function(){var t=Symbol();return!i(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&r&&r<41}))},80236:(t,e,n)=>{var r=n(44931),o=n(78797),i=n(39189),a=n(92446);t.exports=function(){var t=o("Symbol"),e=t&&t.prototype,n=e&&e.valueOf,u=i("toPrimitive");e&&!e[u]&&a(e,u,(function(t){return r(n,this)}),{arity:1})}},5462:(t,e,n)=>{var r=n(12289);t.exports=r&&!!Symbol.for&&!!Symbol.keyFor},21627:(t,e,n)=>{var r,o,i,a,u=n(21833),c=n(33247),s=n(67302),l=n(11055),f=n(34863),p=n(79061),d=n(75527),h=n(72582),y=n(46349),v=n(89614),m=n(19997),g=n(36954),b=u.setImmediate,_=u.clearImmediate,w=u.process,S=u.Dispatch,C=u.Function,E=u.MessageChannel,I=u.String,O=0,P={},T="onreadystatechange";p((function(){r=u.location}));var A=function(t){if(f(P,t)){var e=P[t];delete P[t],e()}},x=function(t){return function(){A(t)}},k=function(t){A(t.data)},R=function(t){u.postMessage(I(t),r.protocol+"//"+r.host)};b&&_||(b=function(t){v(arguments.length,1);var e=l(t)?t:C(t),n=h(arguments,1);return P[++O]=function(){c(e,void 0,n)},o(O),O},_=function(t){delete P[t]},g?o=function(t){w.nextTick(x(t))}:S&&S.now?o=function(t){S.now(x(t))}:E&&!m?(a=(i=new E).port2,i.port1.onmessage=k,o=s(a.postMessage,a)):u.addEventListener&&l(u.postMessage)&&!u.importScripts&&r&&"file:"!==r.protocol&&!p(R)?(o=R,u.addEventListener("message",k,!1)):o=T in y("script")?function(t){d.appendChild(y("script"))[T]=function(){d.removeChild(this),A(t)}}:function(t){setTimeout(x(t),0)}),t.exports={set:b,clear:_}},57746:(t,e,n)=>{var r=n(38982);t.exports=r(1..valueOf)},79036:(t,e,n)=>{var r=n(91129),o=Math.max,i=Math.min;t.exports=function(t,e){var n=r(t);return n<0?o(n+e,0):i(n,e)}},2042:(t,e,n)=>{var r=n(91129),o=n(99536),i=RangeError;t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=o(e);if(e!==n)throw i("Wrong length or index");return n}},4395:(t,e,n)=>{var r=n(7461),o=n(29412);t.exports=function(t){return r(o(t))}},91129:(t,e,n)=>{var r=n(56811);t.exports=function(t){var e=+t;return e!=e||0===e?0:r(e)}},99536:(t,e,n)=>{var r=n(91129),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},50775:(t,e,n)=>{var r=n(29412),o=Object;t.exports=function(t){return o(r(t))}},33983:(t,e,n)=>{var r=n(44931),o=n(96692),i=n(30907),a=n(4224),u=n(2272),c=n(39189),s=TypeError,l=c("toPrimitive");t.exports=function(t,e){if(!o(t)||i(t))return t;var n,c=a(t,l);if(c){if(void 0===e&&(e="default"),n=r(c,t,e),!o(n)||i(n))return n;throw s("Can't convert object to primitive value")}return void 0===e&&(e="number"),u(t,e)}},50243:(t,e,n)=>{var r=n(33983),o=n(30907);t.exports=function(t){var e=r(t,"string");return o(e)?e:e+""}},13878:(t,e,n)=>{var r={};r[n(39189)("toStringTag")]="z",t.exports="[object z]"===String(r)},96641:(t,e,n)=>{var r=n(75493),o=String;t.exports=function(t){if("Symbol"===r(t))throw TypeError("Cannot convert a Symbol value to a string");return o(t)}},79269:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},64550:(t,e,n)=>{var r=n(38982),o=0,i=Math.random(),a=r(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++o+i,36)}},92010:(t,e,n)=>{var r=n(12289);t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},75828:(t,e,n)=>{var r=n(4426),o=n(79061);t.exports=r&&o((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},89614:t=>{var e=TypeError;t.exports=function(t,n){if(t{var r=n(21833),o=n(11055),i=r.WeakMap;t.exports=o(i)&&/native code/.test(String(i))},1749:(t,e,n)=>{var r=n(16665),o=n(34863),i=n(2561),a=n(59143).f;t.exports=function(t){var e=r.Symbol||(r.Symbol={});o(e,t)||a(e,t,{value:i.f(t)})}},2561:(t,e,n)=>{var r=n(39189);e.f=r},39189:(t,e,n)=>{var r=n(21833),o=n(51435),i=n(34863),a=n(64550),u=n(12289),c=n(92010),s=r.Symbol,l=o("wks"),f=c?s.for||s:s&&s.withoutSetter||a;t.exports=function(t){return i(l,t)||(l[t]=u&&i(s,t)?s[t]:f("Symbol."+t)),l[t]}},18986:t=>{t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},33217:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(70668),a=n(18807),u="ArrayBuffer",c=i[u];r({global:!0,constructor:!0,forced:o[u]!==c},{ArrayBuffer:c}),a(u)},79851:(t,e,n)=>{"use strict";var r=n(58288),o=n(46526),i=n(79061),a=n(70668),u=n(90649),c=n(79036),s=n(99536),l=n(46439),f=a.ArrayBuffer,p=a.DataView,d=p.prototype,h=o(f.prototype.slice),y=o(d.getUint8),v=o(d.setUint8);r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:i((function(){return!new f(2).slice(1,void 0).byteLength}))},{slice:function(t,e){if(h&&void 0===e)return h(u(this),t);for(var n=u(this).byteLength,r=c(t,n),o=c(void 0===e?n:e,n),i=new(l(this,f))(s(o-r)),a=new p(this),d=new p(i),m=0;r{"use strict";var r=n(58288),o=n(79061),i=n(57886),a=n(96692),u=n(50775),c=n(12244),s=n(68655),l=n(25762),f=n(88627),p=n(20423),d=n(39189),h=n(36918),y=d("isConcatSpreadable"),v=h>=51||!o((function(){var t=[];return t[y]=!1,t.concat()[0]!==t})),m=function(t){if(!a(t))return!1;var e=t[y];return void 0!==e?!!e:i(t)};r({target:"Array",proto:!0,arity:1,forced:!v||!p("concat")},{concat:function(t){var e,n,r,o,i,a=u(this),p=f(a,0),d=0;for(e=-1,r=arguments.length;e{var r=n(58288),o=n(70419),i=n(44595);r({target:"Array",proto:!0},{fill:o}),i("fill")},14266:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).filter;r({target:"Array",proto:!0,forced:!n(20423)("filter")},{filter:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},11466:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).findIndex,i=n(44595),a="findIndex",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{findIndex:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i(a)},10715:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).find,i=n(44595),a="find",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{find:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i(a)},508:(t,e,n)=>{"use strict";var r=n(58288),o=n(96493),i=n(35476),a=n(50775),u=n(12244),c=n(88627);r({target:"Array",proto:!0},{flatMap:function(t){var e,n=a(this),r=u(n);return i(t),(e=c(n,0)).length=o(e,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),e}})},2184:(t,e,n)=>{var r=n(58288),o=n(36658);r({target:"Array",stat:!0,forced:!n(25542)((function(t){Array.from(t)}))},{from:o})},88477:(t,e,n)=>{"use strict";var r=n(58288),o=n(20895).includes,i=n(79061),a=n(44595);r({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),a("includes")},47818:(t,e,n)=>{"use strict";var r=n(58288),o=n(46526),i=n(20895).indexOf,a=n(46644),u=o([].indexOf),c=!!u&&1/u([1],1,-0)<0;r({target:"Array",proto:!0,forced:c||!a("indexOf")},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return c?u(this,t,e)||0:i(this,t,e)}})},14718:(t,e,n)=>{"use strict";var r=n(4395),o=n(44595),i=n(45347),a=n(58319),u=n(59143).f,c=n(49626),s=n(42579),l=n(59785),f=n(4426),p="Array Iterator",d=a.set,h=a.getterFor(p);t.exports=c(Array,"Array",(function(t,e){d(this,{type:p,target:r(t),index:0,kind:e})}),(function(){var t=h(this),e=t.target,n=t.kind,r=t.index++;return!e||r>=e.length?(t.target=void 0,s(void 0,!0)):s("keys"==n?r:"values"==n?e[r]:[r,e[r]],!1)}),"values");var y=i.Arguments=i.Array;if(o("keys"),o("values"),o("entries"),!l&&f&&"values"!==y.name)try{u(y,"name",{value:"values"})}catch(t){}},57188:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(7461),a=n(4395),u=n(46644),c=o([].join);r({target:"Array",proto:!0,forced:i!=Object||!u("join",",")},{join:function(t){return c(a(this),void 0===t?",":t)}})},35823:(t,e,n)=>{var r=n(58288),o=n(37041);r({target:"Array",proto:!0,forced:o!==[].lastIndexOf},{lastIndexOf:o})},80404:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).map;r({target:"Array",proto:!0,forced:!n(20423)("map")},{map:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},5360:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(57886),a=o([].reverse),u=[1,2];r({target:"Array",proto:!0,forced:String(u)===String(u.reverse())},{reverse:function(){return i(this)&&(this.length=this.length),a(this)}})},44396:(t,e,n)=>{"use strict";var r=n(58288),o=n(57886),i=n(11547),a=n(96692),u=n(79036),c=n(12244),s=n(4395),l=n(25762),f=n(39189),p=n(20423),d=n(72582),h=p("slice"),y=f("species"),v=Array,m=Math.max;r({target:"Array",proto:!0,forced:!h},{slice:function(t,e){var n,r,f,p=s(this),h=c(p),g=u(t,h),b=u(void 0===e?h:e,h);if(o(p)&&(n=p.constructor,(i(n)&&(n===v||o(n.prototype))||a(n)&&null===(n=n[y]))&&(n=void 0),n===v||void 0===n))return d(p,g,b);for(r=new(void 0===n?v:n)(m(b-g,0)),f=0;g{"use strict";var r=n(58288),o=n(38982),i=n(35476),a=n(50775),u=n(12244),c=n(87472),s=n(96641),l=n(79061),f=n(84326),p=n(46644),d=n(27496),h=n(36928),y=n(36918),v=n(53522),m=[],g=o(m.sort),b=o(m.push),_=l((function(){m.sort(void 0)})),w=l((function(){m.sort(null)})),S=p("sort"),C=!l((function(){if(y)return y<70;if(!(d&&d>3)){if(h)return!0;if(v)return v<603;var t,e,n,r,o="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)m.push({k:e+r,v:n})}for(m.sort((function(t,e){return e.v-t.v})),r=0;rs(n)?1:-1}}(t)),n=u(o),r=0;r{"use strict";var r=n(58288),o=n(50775),i=n(79036),a=n(91129),u=n(12244),c=n(41909),s=n(68655),l=n(88627),f=n(25762),p=n(87472),d=n(20423)("splice"),h=Math.max,y=Math.min;r({target:"Array",proto:!0,forced:!d},{splice:function(t,e){var n,r,d,v,m,g,b=o(this),_=u(b),w=i(t,_),S=arguments.length;for(0===S?n=r=0:1===S?(n=0,r=_-w):(n=S-2,r=y(h(a(e),0),_-w)),s(_+n-r),d=l(b,r),v=0;v_-r+n;v--)p(b,v-1)}else if(n>r)for(v=_-r;v>w;v--)g=v+n-1,(m=v+r-1)in b?b[g]=b[m]:p(b,g);for(v=0;v{n(44595)("flatMap")},62342:(t,e,n)=>{var r=n(34863),o=n(92446),i=n(55362),a=n(39189)("toPrimitive"),u=Date.prototype;r(u,a)||o(u,a,i)},18864:(t,e,n)=>{var r=n(4426),o=n(92684).EXISTS,i=n(38982),a=n(61548),u=Function.prototype,c=i(u.toString),s=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,l=i(s.exec);r&&!o&&a(u,"name",{configurable:!0,get:function(){try{return l(s,c(this))[1]}catch(t){return""}}})},81172:(t,e,n)=>{var r=n(58288),o=n(78797),i=n(33247),a=n(44931),u=n(38982),c=n(79061),s=n(11055),l=n(30907),f=n(72582),p=n(54875),d=n(12289),h=String,y=o("JSON","stringify"),v=u(/./.exec),m=u("".charAt),g=u("".charCodeAt),b=u("".replace),_=u(1..toString),w=/[\uD800-\uDFFF]/g,S=/^[\uD800-\uDBFF]$/,C=/^[\uDC00-\uDFFF]$/,E=!d||c((function(){var t=o("Symbol")();return"[null]"!=y([t])||"{}"!=y({a:t})||"{}"!=y(Object(t))})),I=c((function(){return'"\\udf06\\ud834"'!==y("\udf06\ud834")||'"\\udead"'!==y("\udead")})),O=function(t,e){var n=f(arguments),r=p(e);if(s(r)||void 0!==t&&!l(t))return n[1]=function(t,e){if(s(r)&&(e=a(r,this,h(t),e)),!l(e))return e},i(y,null,n)},P=function(t,e,n){var r=m(n,e-1),o=m(n,e+1);return v(S,t)&&!v(C,o)||v(C,t)&&!v(S,r)?"\\u"+_(g(t,0),16):t};y&&r({target:"JSON",stat:!0,arity:3,forced:E||I},{stringify:function(t,e,n){var r=f(arguments),o=i(E?O:y,null,r);return I&&"string"==typeof o?b(o,w,P):o}})},54513:(t,e,n)=>{"use strict";n(35365)("Map",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(49720))},20363:(t,e,n)=>{n(54513)},25226:(t,e,n)=>{"use strict";var r=n(58288),o=n(59785),i=n(4426),a=n(21833),u=n(16665),c=n(38982),s=n(96942),l=n(34863),f=n(86953),p=n(47931),d=n(30907),h=n(33983),y=n(79061),v=n(47210).f,m=n(77637).f,g=n(59143).f,b=n(57746),_=n(92572).trim,w="Number",S=a[w],C=u[w],E=S.prototype,I=a.TypeError,O=c("".slice),P=c("".charCodeAt),T=s(w,!S(" 0o1")||!S("0b1")||S("+0x1")),A=function(t){var e,n=arguments.length<1?0:S(function(t){var e=h(t,"number");return"bigint"==typeof e?e:function(t){var e,n,r,o,i,a,u,c,s=h(t,"number");if(d(s))throw I("Cannot convert a Symbol value to a number");if("string"==typeof s&&s.length>2)if(s=_(s),43===(e=P(s,0))||45===e){if(88===(n=P(s,2))||120===n)return NaN}else if(48===e){switch(P(s,1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+s}for(a=(i=O(s,2)).length,u=0;uo)return NaN;return parseInt(i,r)}return+s}(e)}(t));return p(E,e=this)&&y((function(){b(e)}))?f(Object(n),this,A):n};A.prototype=E,T&&!o&&(E.constructor=A),r({global:!0,constructor:!0,wrap:!0,forced:T},{Number:A});var x=function(t,e){for(var n,r=i?v(e):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),o=0;r.length>o;o++)l(e,n=r[o])&&!l(t,n)&&g(t,n,m(e,n))};o&&C&&x(u[w],C),(T||o)&&x(u[w],S)},69204:(t,e,n)=>{n(58288)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},90291:(t,e,n)=>{var r=n(58288),o=n(58187);r({target:"Object",stat:!0,arity:2,forced:Object.assign!==o},{assign:o})},976:(t,e,n)=>{var r=n(58288),o=n(70671).entries;r({target:"Object",stat:!0},{entries:function(t){return o(t)}})},56949:(t,e,n)=>{var r=n(58288),o=n(1566),i=n(79061),a=n(96692),u=n(89277).onFreeze,c=Object.freeze;r({target:"Object",stat:!0,forced:i((function(){c(1)})),sham:!o},{freeze:function(t){return c&&a(t)?c(u(t)):t}})},15277:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(4395),a=n(77637).f,u=n(4426);r({target:"Object",stat:!0,forced:!u||o((function(){a(1)})),sham:!u},{getOwnPropertyDescriptor:function(t,e){return a(i(t),e)}})},32194:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(83744).f;r({target:"Object",stat:!0,forced:o((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:i})},69047:(t,e,n)=>{var r=n(58288),o=n(12289),i=n(79061),a=n(68255),u=n(50775);r({target:"Object",stat:!0,forced:!o||i((function(){a.f(1)}))},{getOwnPropertySymbols:function(t){var e=a.f;return e?e(u(t)):[]}})},46977:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(50775),a=n(52473),u=n(16797);r({target:"Object",stat:!0,forced:o((function(){a(1)})),sham:!u},{getPrototypeOf:function(t){return a(i(t))}})},38085:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(96692),a=n(17170),u=n(65642),c=Object.isFrozen;r({target:"Object",stat:!0,forced:u||o((function(){c(1)}))},{isFrozen:function(t){return!i(t)||!(!u||"ArrayBuffer"!=a(t))||!!c&&c(t)}})},21894:(t,e,n)=>{var r=n(58288),o=n(50775),i=n(80094);r({target:"Object",stat:!0,forced:n(79061)((function(){i(1)}))},{keys:function(t){return i(o(t))}})},68461:(t,e,n)=>{n(58288)({target:"Object",stat:!0},{setPrototypeOf:n(26213)})},13521:(t,e,n)=>{var r=n(13878),o=n(92446),i=n(42553);r||o(Object.prototype,"toString",i,{unsafe:!0})},8933:(t,e,n)=>{var r=n(58288),o=n(55870);r({global:!0,forced:parseFloat!=o},{parseFloat:o})},17186:(t,e,n)=>{var r=n(58288),o=n(145);r({global:!0,forced:parseInt!=o},{parseInt:o})},47333:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(35476),a=n(76185),u=n(63341),c=n(4846);r({target:"Promise",stat:!0,forced:n(32291)},{all:function(t){var e=this,n=a.f(e),r=n.resolve,s=n.reject,l=u((function(){var n=i(e.resolve),a=[],u=0,l=1;c(t,(function(t){var i=u++,c=!1;l++,o(n,e,t).then((function(t){c||(c=!0,a[i]=t,--l||r(a))}),s)})),--l||r(a)}));return l.error&&s(l.value),n.promise}})},8269:(t,e,n)=>{"use strict";var r=n(58288),o=n(59785),i=n(43322).CONSTRUCTOR,a=n(70828),u=n(78797),c=n(11055),s=n(92446),l=a&&a.prototype;if(r({target:"Promise",proto:!0,forced:i,real:!0},{catch:function(t){return this.then(void 0,t)}}),!o&&c(a)){var f=u("Promise").prototype.catch;l.catch!==f&&s(l,"catch",f,{unsafe:!0})}},37214:(t,e,n)=>{"use strict";var r,o,i,a=n(58288),u=n(59785),c=n(36954),s=n(21833),l=n(44931),f=n(92446),p=n(26213),d=n(49233),h=n(18807),y=n(35476),v=n(11055),m=n(96692),g=n(37809),b=n(46439),_=n(21627).set,w=n(26269),S=n(69991),C=n(63341),E=n(72879),I=n(58319),O=n(70828),P=n(43322),T=n(76185),A="Promise",x=P.CONSTRUCTOR,k=P.REJECTION_EVENT,R=P.SUBCLASSING,M=I.getterFor(A),j=I.set,N=O&&O.prototype,D=O,L=N,z=s.TypeError,U=s.document,F=s.process,B=T.f,q=B,V=!!(U&&U.createEvent&&s.dispatchEvent),G="unhandledrejection",H=function(t){var e;return!(!m(t)||!v(e=t.then))&&e},Y=function(t,e){var n,r,o,i=e.value,a=1==e.state,u=a?t.ok:t.fail,c=t.resolve,s=t.reject,f=t.domain;try{u?(a||(2===e.rejection&&Z(e),e.rejection=1),!0===u?n=i:(f&&f.enter(),n=u(i),f&&(f.exit(),o=!0)),n===t.promise?s(z("Promise-chain cycle")):(r=H(n))?l(r,n,c,s):c(n)):s(i)}catch(t){f&&!o&&f.exit(),s(t)}},W=function(t,e){t.notified||(t.notified=!0,w((function(){for(var n,r=t.reactions;n=r.get();)Y(n,t);t.notified=!1,e&&!t.rejection&&$(t)})))},K=function(t,e,n){var r,o;V?((r=U.createEvent("Event")).promise=e,r.reason=n,r.initEvent(t,!1,!0),s.dispatchEvent(r)):r={promise:e,reason:n},!k&&(o=s["on"+t])?o(r):t===G&&S("Unhandled promise rejection",n)},$=function(t){l(_,s,(function(){var e,n=t.facade,r=t.value;if(Q(t)&&(e=C((function(){c?F.emit("unhandledRejection",r,n):K(G,n,r)})),t.rejection=c||Q(t)?2:1,e.error))throw e.value}))},Q=function(t){return 1!==t.rejection&&!t.parent},Z=function(t){l(_,s,(function(){var e=t.facade;c?F.emit("rejectionHandled",e):K("rejectionhandled",e,t.value)}))},J=function(t,e,n){return function(r){t(e,r,n)}},X=function(t,e,n){t.done||(t.done=!0,n&&(t=n),t.value=e,t.state=2,W(t,!0))},tt=function(t,e,n){if(!t.done){t.done=!0,n&&(t=n);try{if(t.facade===e)throw z("Promise can't be resolved itself");var r=H(e);r?w((function(){var n={done:!1};try{l(r,e,J(tt,n,t),J(X,n,t))}catch(e){X(n,e,t)}})):(t.value=e,t.state=1,W(t,!1))}catch(e){X({done:!1},e,t)}}};if(x&&(L=(D=function(t){g(this,L),y(t),l(r,this);var e=M(this);try{t(J(tt,e),J(X,e))}catch(t){X(e,t)}}).prototype,(r=function(t){j(this,{type:A,done:!1,notified:!1,parent:!1,reactions:new E,rejection:!1,state:0,value:void 0})}).prototype=f(L,"then",(function(t,e){var n=M(this),r=B(b(this,D));return n.parent=!0,r.ok=!v(t)||t,r.fail=v(e)&&e,r.domain=c?F.domain:void 0,0==n.state?n.reactions.add(r):w((function(){Y(r,n)})),r.promise})),o=function(){var t=new r,e=M(t);this.promise=t,this.resolve=J(tt,e),this.reject=J(X,e)},T.f=B=function(t){return t===D||void 0===t?new o(t):q(t)},!u&&v(O)&&N!==Object.prototype)){i=N.then,R||f(N,"then",(function(t,e){var n=this;return new D((function(t,e){l(i,n,t,e)})).then(t,e)}),{unsafe:!0});try{delete N.constructor}catch(t){}p&&p(N,L)}a({global:!0,constructor:!0,wrap:!0,forced:x},{Promise:D}),d(D,A,!1,!0),h(A)},67536:(t,e,n)=>{n(37214),n(47333),n(8269),n(7757),n(16811),n(73938)},7757:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(35476),a=n(76185),u=n(63341),c=n(4846);r({target:"Promise",stat:!0,forced:n(32291)},{race:function(t){var e=this,n=a.f(e),r=n.reject,s=u((function(){var a=i(e.resolve);c(t,(function(t){o(a,e,t).then(n.resolve,r)}))}));return s.error&&r(s.value),n.promise}})},16811:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(76185);r({target:"Promise",stat:!0,forced:n(43322).CONSTRUCTOR},{reject:function(t){var e=i.f(this);return o(e.reject,void 0,t),e.promise}})},73938:(t,e,n)=>{"use strict";var r=n(58288),o=n(78797),i=n(59785),a=n(70828),u=n(43322).CONSTRUCTOR,c=n(77472),s=o("Promise"),l=i&&!u;r({target:"Promise",stat:!0,forced:i||u},{resolve:function(t){return c(l&&this===s?a:this,t)}})},84090:(t,e,n)=>{var r=n(4426),o=n(21833),i=n(38982),a=n(96942),u=n(86953),c=n(69193),s=n(47210).f,l=n(47931),f=n(16030),p=n(96641),d=n(84228),h=n(60303),y=n(76434),v=n(92446),m=n(79061),g=n(34863),b=n(58319).enforce,_=n(18807),w=n(39189),S=n(99121),C=n(90324),E=w("match"),I=o.RegExp,O=I.prototype,P=o.SyntaxError,T=i(O.exec),A=i("".charAt),x=i("".replace),k=i("".indexOf),R=i("".slice),M=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,j=/a/g,N=/a/g,D=new I(j)!==j,L=h.MISSED_STICKY,z=h.UNSUPPORTED_Y;if(a("RegExp",r&&(!D||L||S||C||m((function(){return N[E]=!1,I(j)!=j||I(N)==N||"/a/i"!=I(j,"i")}))))){for(var U=function(t,e){var n,r,o,i,a,s,h=l(O,this),y=f(t),v=void 0===e,m=[],_=t;if(!h&&y&&v&&t.constructor===U)return t;if((y||l(O,t))&&(t=t.source,v&&(e=d(_))),t=void 0===t?"":p(t),e=void 0===e?"":p(e),_=t,S&&"dotAll"in j&&(r=!!e&&k(e,"s")>-1)&&(e=x(e,/s/g,"")),n=e,L&&"sticky"in j&&(o=!!e&&k(e,"y")>-1)&&z&&(e=x(e,/y/g,"")),C&&(i=function(t){for(var e,n=t.length,r=0,o="",i=[],a={},u=!1,c=!1,s=0,l="";r<=n;r++){if("\\"===(e=A(t,r)))e+=A(t,++r);else if("]"===e)u=!1;else if(!u)switch(!0){case"["===e:u=!0;break;case"("===e:T(M,R(t,r+1))&&(r+=2,c=!0),o+=e,s++;continue;case">"===e&&c:if(""===l||g(a,l))throw new P("Invalid capture group name");a[l]=!0,i[i.length]=[l,s],c=!1,l="";continue}c?l+=e:o+=e}return[o,i]}(t),t=i[0],m=i[1]),a=u(I(t,e),h?this:O,U),(r||o||m.length)&&(s=b(a),r&&(s.dotAll=!0,s.raw=U(function(t){for(var e,n=t.length,r=0,o="",i=!1;r<=n;r++)"\\"!==(e=A(t,r))?i||"."!==e?("["===e?i=!0:"]"===e&&(i=!1),o+=e):o+="[\\s\\S]":o+=e+A(t,++r);return o}(t),n)),o&&(s.sticky=!0),m.length&&(s.groups=m)),t!==_)try{c(a,"source",""===_?"(?:)":_)}catch(t){}return a},F=s(I),B=0;F.length>B;)y(U,I,F[B++]);O.constructor=U,U.prototype=O,v(o,"RegExp",U,{constructor:!0})}_("RegExp")},18489:(t,e,n)=>{"use strict";var r=n(58288),o=n(74989);r({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},88315:(t,e,n)=>{"use strict";var r=n(92684).PROPER,o=n(92446),i=n(90649),a=n(96641),u=n(79061),c=n(84228),s="toString",l=RegExp.prototype[s],f=u((function(){return"/a/b"!=l.call({source:"a",flags:"b"})})),p=r&&l.name!=s;(f||p)&&o(RegExp.prototype,s,(function(){var t=i(this);return"/"+a(t.source)+"/"+a(c(t))}),{unsafe:!0})},58055:(t,e,n)=>{"use strict";n(35365)("Set",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(49720))},65669:(t,e,n)=>{n(58055)},52063:(t,e,n)=>{"use strict";var r,o=n(58288),i=n(46526),a=n(77637).f,u=n(99536),c=n(96641),s=n(15425),l=n(29412),f=n(59494),p=n(59785),d=i("".endsWith),h=i("".slice),y=Math.min,v=f("endsWith");o({target:"String",proto:!0,forced:!(!p&&!v&&(r=a(String.prototype,"endsWith"),r&&!r.writable)||v)},{endsWith:function(t){var e=c(l(this));s(t);var n=arguments.length>1?arguments[1]:void 0,r=e.length,o=void 0===n?r:y(u(n),r),i=c(t);return d?d(e,i,o):h(e,o-i.length,o)===i}})},35157:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(15425),a=n(29412),u=n(96641),c=n(59494),s=o("".indexOf);r({target:"String",proto:!0,forced:!c("includes")},{includes:function(t){return!!~s(u(a(this)),u(i(t)),arguments.length>1?arguments[1]:void 0)}})},25766:(t,e,n)=>{"use strict";var r=n(65877).charAt,o=n(96641),i=n(58319),a=n(49626),u=n(42579),c="String Iterator",s=i.set,l=i.getterFor(c);a(String,"String",(function(t){s(this,{type:c,string:o(t),index:0})}),(function(){var t,e=l(this),n=e.string,o=e.index;return o>=n.length?u(void 0,!0):(t=r(n,o),e.index+=t.length,u(t,!1))}))},54232:(t,e,n)=>{"use strict";var r=n(58288),o=n(68662);r({target:"String",proto:!0,forced:n(15927)("link")},{link:function(t){return o(this,"a","href",t)}})},95743:(t,e,n)=>{"use strict";var r=n(44931),o=n(35146),i=n(90649),a=n(40899),u=n(99536),c=n(96641),s=n(29412),l=n(4224),f=n(78839),p=n(47160);o("match",(function(t,e,n){return[function(e){var n=s(this),o=a(e)?void 0:l(e,t);return o?r(o,e,n):new RegExp(e)[t](c(n))},function(t){var r=i(this),o=c(t),a=n(e,r,o);if(a.done)return a.value;if(!r.global)return p(r,o);var s=r.unicode;r.lastIndex=0;for(var l,d=[],h=0;null!==(l=p(r,o));){var y=c(l[0]);d[h]=y,""===y&&(r.lastIndex=f(o,u(r.lastIndex),s)),h++}return 0===h?null:d}]}))},7771:(t,e,n)=>{"use strict";var r=n(58288),o=n(8439).end;r({target:"String",proto:!0,forced:n(96929)},{padEnd:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},20902:(t,e,n)=>{"use strict";var r=n(58288),o=n(8439).start;r({target:"String",proto:!0,forced:n(96929)},{padStart:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},77071:(t,e,n)=>{n(58288)({target:"String",proto:!0},{repeat:n(20471)})},53618:(t,e,n)=>{"use strict";var r=n(33247),o=n(44931),i=n(38982),a=n(35146),u=n(79061),c=n(90649),s=n(11055),l=n(40899),f=n(91129),p=n(99536),d=n(96641),h=n(29412),y=n(78839),v=n(4224),m=n(34032),g=n(47160),b=n(39189)("replace"),_=Math.max,w=Math.min,S=i([].concat),C=i([].push),E=i("".indexOf),I=i("".slice),O="$0"==="a".replace(/./,"$0"),P=!!/./[b]&&""===/./[b]("a","$0");a("replace",(function(t,e,n){var i=P?"$":"$0";return[function(t,n){var r=h(this),i=l(t)?void 0:v(t,b);return i?o(i,t,r,n):o(e,d(r),t,n)},function(t,o){var a=c(this),u=d(t);if("string"==typeof o&&-1===E(o,i)&&-1===E(o,"$<")){var l=n(e,a,u,o);if(l.done)return l.value}var h=s(o);h||(o=d(o));var v=a.global;if(v){var b=a.unicode;a.lastIndex=0}for(var O=[];;){var P=g(a,u);if(null===P)break;if(C(O,P),!v)break;""===d(P[0])&&(a.lastIndex=y(u,p(a.lastIndex),b))}for(var T,A="",x=0,k=0;k=x&&(A+=I(u,x,M)+z,x=M+R.length)}return A+I(u,x)}]}),!!u((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$")}))||!O||P)},27188:(t,e,n)=>{"use strict";var r=n(44931),o=n(35146),i=n(90649),a=n(40899),u=n(29412),c=n(45448),s=n(96641),l=n(4224),f=n(47160);o("search",(function(t,e,n){return[function(e){var n=u(this),o=a(e)?void 0:l(e,t);return o?r(o,e,n):new RegExp(e)[t](s(n))},function(t){var r=i(this),o=s(t),a=n(e,r,o);if(a.done)return a.value;var u=r.lastIndex;c(u,0)||(r.lastIndex=0);var l=f(r,o);return c(r.lastIndex,u)||(r.lastIndex=u),null===l?-1:l.index}]}))},11062:(t,e,n)=>{"use strict";var r=n(33247),o=n(44931),i=n(38982),a=n(35146),u=n(90649),c=n(40899),s=n(16030),l=n(29412),f=n(46439),p=n(78839),d=n(99536),h=n(96641),y=n(4224),v=n(10301),m=n(47160),g=n(74989),b=n(60303),_=n(79061),w=b.UNSUPPORTED_Y,S=4294967295,C=Math.min,E=[].push,I=i(/./.exec),O=i(E),P=i("".slice);a("split",(function(t,e,n){var i;return i="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var i=h(l(this)),a=void 0===n?S:n>>>0;if(0===a)return[];if(void 0===t)return[i];if(!s(t))return o(e,i,t,a);for(var u,c,f,p=[],d=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),y=0,m=new RegExp(t.source,d+"g");(u=o(g,m,i))&&!((c=m.lastIndex)>y&&(O(p,P(i,y,u.index)),u.length>1&&u.index=a));)m.lastIndex===u.index&&m.lastIndex++;return y===i.length?!f&&I(m,"")||O(p,""):O(p,P(i,y)),p.length>a?v(p,0,a):p}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:o(e,this,t,n)}:e,[function(e,n){var r=l(this),a=c(e)?void 0:y(e,t);return a?o(a,e,r,n):o(i,h(r),e,n)},function(t,r){var o=u(this),a=h(t),c=n(i,o,a,r,i!==e);if(c.done)return c.value;var s=f(o,RegExp),l=o.unicode,y=(o.ignoreCase?"i":"")+(o.multiline?"m":"")+(o.unicode?"u":"")+(w?"g":"y"),v=new s(w?"^(?:"+o.source+")":o,y),g=void 0===r?S:r>>>0;if(0===g)return[];if(0===a.length)return null===m(v,a)?[a]:[];for(var b=0,_=0,E=[];_{"use strict";var r,o=n(58288),i=n(46526),a=n(77637).f,u=n(99536),c=n(96641),s=n(15425),l=n(29412),f=n(59494),p=n(59785),d=i("".startsWith),h=i("".slice),y=Math.min,v=f("startsWith");o({target:"String",proto:!0,forced:!(!p&&!v&&(r=a(String.prototype,"startsWith"),r&&!r.writable)||v)},{startsWith:function(t){var e=c(l(this));s(t);var n=u(y(arguments.length>1?arguments[1]:void 0,e.length)),r=c(t);return d?d(e,r,n):h(e,n,n+r.length)===r}})},63632:(t,e,n)=>{n(93795);var r=n(58288),o=n(92024);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==o},{trimEnd:o})},91360:(t,e,n)=>{var r=n(58288),o=n(10409);r({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==o},{trimLeft:o})},93795:(t,e,n)=>{var r=n(58288),o=n(92024);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==o},{trimRight:o})},76241:(t,e,n)=>{n(91360);var r=n(58288),o=n(10409);r({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==o},{trimStart:o})},948:(t,e,n)=>{"use strict";var r=n(58288),o=n(92572).trim;r({target:"String",proto:!0,forced:n(4160)("trim")},{trim:function(){return o(this)}})},43366:(t,e,n)=>{n(1749)("asyncIterator")},11399:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(44931),a=n(38982),u=n(59785),c=n(4426),s=n(12289),l=n(79061),f=n(34863),p=n(47931),d=n(90649),h=n(4395),y=n(50243),v=n(96641),m=n(52302),g=n(32814),b=n(80094),_=n(47210),w=n(83744),S=n(68255),C=n(77637),E=n(59143),I=n(2459),O=n(46391),P=n(92446),T=n(61548),A=n(51435),x=n(40693),k=n(43343),R=n(64550),M=n(39189),j=n(2561),N=n(1749),D=n(80236),L=n(49233),z=n(58319),U=n(31567).forEach,F=x("hidden"),B="Symbol",q="prototype",V=z.set,G=z.getterFor(B),H=Object[q],Y=o.Symbol,W=Y&&Y[q],K=o.TypeError,$=o.QObject,Q=C.f,Z=E.f,J=w.f,X=O.f,tt=a([].push),et=A("symbols"),nt=A("op-symbols"),rt=A("wks"),ot=!$||!$[q]||!$[q].findChild,it=c&&l((function(){return 7!=g(Z({},"a",{get:function(){return Z(this,"a",{value:7}).a}})).a}))?function(t,e,n){var r=Q(H,e);r&&delete H[e],Z(t,e,n),r&&t!==H&&Z(H,e,r)}:Z,at=function(t,e){var n=et[t]=g(W);return V(n,{type:B,tag:t,description:e}),c||(n.description=e),n},ut=function(t,e,n){t===H&&ut(nt,e,n),d(t);var r=y(e);return d(n),f(et,r)?(n.enumerable?(f(t,F)&&t[F][r]&&(t[F][r]=!1),n=g(n,{enumerable:m(0,!1)})):(f(t,F)||Z(t,F,m(1,{})),t[F][r]=!0),it(t,r,n)):Z(t,r,n)},ct=function(t,e){d(t);var n=h(e),r=b(n).concat(pt(n));return U(r,(function(e){c&&!i(st,n,e)||ut(t,e,n[e])})),t},st=function(t){var e=y(t),n=i(X,this,e);return!(this===H&&f(et,e)&&!f(nt,e))&&(!(n||!f(this,e)||!f(et,e)||f(this,F)&&this[F][e])||n)},lt=function(t,e){var n=h(t),r=y(e);if(n!==H||!f(et,r)||f(nt,r)){var o=Q(n,r);return!o||!f(et,r)||f(n,F)&&n[F][r]||(o.enumerable=!0),o}},ft=function(t){var e=J(h(t)),n=[];return U(e,(function(t){f(et,t)||f(k,t)||tt(n,t)})),n},pt=function(t){var e=t===H,n=J(e?nt:h(t)),r=[];return U(n,(function(t){!f(et,t)||e&&!f(H,t)||tt(r,et[t])})),r};s||(P(W=(Y=function(){if(p(W,this))throw K("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?v(arguments[0]):void 0,e=R(t),n=function(t){this===H&&i(n,nt,t),f(this,F)&&f(this[F],e)&&(this[F][e]=!1),it(this,e,m(1,t))};return c&&ot&&it(H,e,{configurable:!0,set:n}),at(e,t)})[q],"toString",(function(){return G(this).tag})),P(Y,"withoutSetter",(function(t){return at(R(t),t)})),O.f=st,E.f=ut,I.f=ct,C.f=lt,_.f=w.f=ft,S.f=pt,j.f=function(t){return at(M(t),t)},c&&(T(W,"description",{configurable:!0,get:function(){return G(this).description}}),u||P(H,"propertyIsEnumerable",st,{unsafe:!0}))),r({global:!0,constructor:!0,wrap:!0,forced:!s,sham:!s},{Symbol:Y}),U(b(rt),(function(t){N(t)})),r({target:B,stat:!0,forced:!s},{useSetter:function(){ot=!0},useSimple:function(){ot=!1}}),r({target:"Object",stat:!0,forced:!s,sham:!c},{create:function(t,e){return void 0===e?g(t):ct(g(t),e)},defineProperty:ut,defineProperties:ct,getOwnPropertyDescriptor:lt}),r({target:"Object",stat:!0,forced:!s},{getOwnPropertyNames:ft}),D(),L(Y,B),k[F]=!0},27481:(t,e,n)=>{"use strict";var r=n(58288),o=n(4426),i=n(21833),a=n(38982),u=n(34863),c=n(11055),s=n(47931),l=n(96641),f=n(61548),p=n(14938),d=i.Symbol,h=d&&d.prototype;if(o&&c(d)&&(!("description"in h)||void 0!==d().description)){var y={},v=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:l(arguments[0]),e=s(h,this)?new d(t):void 0===t?d():d(t);return""===t&&(y[e]=!0),e};p(v,d),v.prototype=h,h.constructor=v;var m="Symbol(test)"==String(d("test")),g=a(h.valueOf),b=a(h.toString),_=/^Symbol\((.*)\)[^)]+$/,w=a("".replace),S=a("".slice);f(h,"description",{configurable:!0,get:function(){var t=g(this);if(u(y,t))return"";var e=b(t),n=m?S(e,7,-1):w(e,_,"$1");return""===n?void 0:n}}),r({global:!0,constructor:!0,forced:!0},{Symbol:v})}},51928:(t,e,n)=>{var r=n(58288),o=n(78797),i=n(34863),a=n(96641),u=n(51435),c=n(5462),s=u("string-to-symbol-registry"),l=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!c},{for:function(t){var e=a(t);if(i(s,e))return s[e];var n=o("Symbol")(e);return s[e]=n,l[n]=e,n}})},90105:(t,e,n)=>{n(1749)("iterator")},91621:(t,e,n)=>{n(11399),n(51928),n(88794),n(81172),n(69047)},88794:(t,e,n)=>{var r=n(58288),o=n(34863),i=n(30907),a=n(79269),u=n(51435),c=n(5462),s=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!c},{keyFor:function(t){if(!i(t))throw TypeError(a(t)+" is not a symbol");if(o(s,t))return s[t]}})},11138:(t,e,n)=>{var r=n(1749),o=n(80236);r("toPrimitive"),o()},81676:(t,e,n)=>{"use strict";var r,o=n(1566),i=n(21833),a=n(38982),u=n(14101),c=n(89277),s=n(35365),l=n(42715),f=n(96692),p=n(58319).enforce,d=n(79061),h=n(74528),y=Object,v=Array.isArray,m=y.isExtensible,g=y.isFrozen,b=y.isSealed,_=y.freeze,w=y.seal,S={},C={},E=!i.ActiveXObject&&"ActiveXObject"in i,I=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},O=s("WeakMap",I,l),P=O.prototype,T=a(P.set);if(h)if(E){r=l.getConstructor(I,"WeakMap",!0),c.enable();var A=a(P.delete),x=a(P.has),k=a(P.get);u(P,{delete:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),A(this,t)||e.frozen.delete(t)}return A(this,t)},has:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),x(this,t)||e.frozen.has(t)}return x(this,t)},get:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),x(this,t)?k(this,t):e.frozen.get(t)}return k(this,t)},set:function(t,e){if(f(t)&&!m(t)){var n=p(this);n.frozen||(n.frozen=new r),x(this,t)?T(this,t,e):n.frozen.set(t,e)}else T(this,t,e);return this}})}else o&&d((function(){var t=_([]);return T(new O,t,1),!g(t)}))&&u(P,{set:function(t,e){var n;return v(t)&&(g(t)?n=S:b(t)&&(n=C)),T(this,t,e),n==S&&_(t),n==C&&w(t),this}})},11530:(t,e,n)=>{n(81676)},44594:(t,e,n)=>{var r=n(21833),o=n(4774),i=n(4474),a=n(9877),u=n(69193),c=function(t){if(t&&t.forEach!==a)try{u(t,"forEach",a)}catch(e){t.forEach=a}};for(var s in o)o[s]&&c(r[s]&&r[s].prototype);c(i)},92947:(t,e,n)=>{var r=n(21833),o=n(4774),i=n(4474),a=n(14718),u=n(69193),c=n(39189),s=c("iterator"),l=c("toStringTag"),f=a.values,p=function(t,e){if(t){if(t[s]!==f)try{u(t,s,f)}catch(e){t[s]=f}if(t[l]||u(t,l,e),o[e])for(var n in a)if(t[n]!==a[n])try{u(t,n,a[n])}catch(e){t[n]=a[n]}}};for(var d in o)p(r[d]&&r[d].prototype,d);p(i,"DOMTokenList")},18342:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931);r({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return o(URL.prototype.toString,this)}})}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={id:r,loaded:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t);var r={};return(()=>{"use strict";n.r(r),n.d(r,{createCheckoutButtonInitializer:()=>Eh,createTimeout:()=>o.createTimeout});var t={};n.r(t),n.d(t,{createAmazonPayV2ButtonStrategy:()=>yl,createApplePayButtonStrategy:()=>Bl,createBoltButtonStrategy:()=>ef,createBraintreeVenmoButtonStrategy:()=>mf,createBraintreeVisaCheckoutButtonStrategy:()=>cf,createGooglePayAdyenV2ButtonStrategy:()=>mp,createGooglePayAdyenV3ButtonStrategy:()=>gp,createGooglePayAuthorizeDotNetButtonStrategy:()=>Sp,createGooglePayBraintreeButtonStrategy:()=>op,createGooglePayCheckoutComButtonStrategy:()=>xp,createGooglePayCybersourceButtonStrategy:()=>jp,createGooglePayOrbitalButtonStrategy:()=>zp,createGooglePayPayPalCommerceButtonStrategy:()=>vp,createGooglePayStripeButtonStrategy:()=>Zp,createGooglePayTdOnlineMartButtonStrategy:()=>cd,createGooglePayWorldpayAccessButtonStrategy:()=>ed,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>sh,createPayPalCommerceButtonStrategy:()=>Ud,createPayPalCommerceCreditButtonStrategy:()=>Zd,createPayPalCommerceVenmoButtonStrategy:()=>rh,createPaypalExpressButtonStrategy:()=>Ch});var e,o=n(9285),i=n(74152),a=(n(90291),n(99840)),u=(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)},function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)});const c=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return u(e,t),e}(Error);var s=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),l={body:{},headers:{},status:0},f=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,u=e||l,c=u.body,s=u.headers,f=u.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=s,a.status=f,a.errors=i||[],a}return s(e,t),e}(c);const p=f;var d=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const h=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return d(e,t),e}(p);n(18864),n(68461);var y,v=(y=function(t,e){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},y(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}y(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return v(e,t),e}(Error);var g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),b={body:{},headers:{},status:0},_=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,u=e||b,c=u.body,s=u.headers,l=u.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=s,a.status=l,a.errors=i||[],a}return g(e,t),e}(m);const w=_;var S=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const C=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return S(e,t),e}(w);n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(11062),n(92947);var E=n(45550),I=(n(98556),n(57188),n(80404),n(44396),function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o-1){var o=n[r];return r>0&&(n.splice(r,1),n.unshift(o)),o.value}return or}return{get:r,put:function(e,o){r(e)===or&&(n.unshift({key:e,value:o}),n.length>t&&n.pop())},getEntries:function(){return n},clear:function(){n=[]}}}(c,l);function p(){var e=f.get(arguments);if(e===or){if(e=t.apply(null,arguments),s){var n=f.getEntries().find((function(t){return s(t.value,e)}));n&&(e=n.value)}f.put(arguments,e)}return e}return p.clearCache=function(){return f.clear()},p}function ur(t){return ur="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ur(t)}function cr(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r0}})),Y=lr(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===br||t()===_r}})),(0,tr.B4)((function(t,e){return{getPaymentId:L({checkout:t,order:e}),getPaymentIdOrThrow:z({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:F({checkout:t,order:e}),getPaymentToken:B({checkout:t,order:e}),getPaymentTokenOrThrow:q({checkout:t,order:e}),getPaymentRedirectUrl:V({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:G({checkout:t,order:e}),isPaymentDataRequired:H({checkout:t,order:e}),isPaymentDataSubmitted:Y({checkout:t,order:e})}}))),Et=function(){var t=lr((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=lr((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,tr.B4)((function(n){return void 0===n&&(n=Cr),{getApplyError:t(n),isApplying:e(n)}}))}(),It=function(){var t=lr((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=lr((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,tr.B4)((function(n){return void 0===n&&(n=Gn),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Ot=(W=lr((function(t){return t.data}),(function(t){return function(){return t}})),K=lr((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),$=lr((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,tr.B4)((function(t){return void 0===t&&(t=jn),{getEmail:W(t),getSendError:K(t),isSending:$(t)}}))),Pt=function(){var t=lr((function(t){return t.data}),(function(t){return function(){return t}})),e=lr((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=lr((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=lr((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,tr.B4)((function(o){return void 0===o&&(o=Xt),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n=Z(t.billingAddress),r=J(t.cart),o=X(t.checkoutButton),i=et(t.countries),a=nt(t.coupons),u=rt(t.customer),c=ot(t.customerStrategies),s=Pt(t.extensions),l=ut(t.formFields),f=it(t.giftCertificates),p=at(t.instruments),d=wt(t.orderBillingAddress),h=st(t.paymentMethods),y=pt(t.paymentProviderCustomer),v=lt(t.paymentStrategies),m=ft(t.pickupOptions),g=dt(t.remoteCheckout),b=yt(t.consignments),_=vt(t.shippingCountries),w=mt(t.shippingStrategies),S=It(t.subscriptions),C=Et(t.storeCredit),E=Ot(t.signInEmail),I=gt(t.consignments,r),O=bt(t.checkout,n,r,I,a,u,f),P=_t(t.order,d,a),T=St(O,P),A={billingAddress:n,cart:r,checkout:O,checkoutButton:o,config:tt(t.config,t.formFields),consignments:I,countries:i,coupons:a,customer:u,customerStrategies:c,extensions:s,form:l,giftCertificates:f,instruments:p,order:P,orderBillingAddress:d,payment:T,paymentMethods:h,paymentProviderCustomer:y,paymentStrategies:v,pickupOptions:m,remoteCheckout:g,shippingAddress:b,shippingCountries:_,shippingStrategies:w,signInEmail:E,subscriptions:S,storeCredit:C};return e.shouldWarnMutation?function(t){return Object.keys(t).reduce((function(e,n){return e[n]=hr(t[n]),e}),{})}(A):A}}var Or=function(){return Or=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadPaymentMethod",null),t}();const Lr=Dr;var zr;!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(zr||(zr={}));const Ur=zr;var Fr="This API endpoint is for internal use only and may change in the future",Br={"X-Checkout-SDK-Version":"1.695.2"},qr=function(){return qr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new wo(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,u="/api/storefront/checkout/".concat(t),c=So({Accept:Ur.JsonV1},Br);return this._requestSender.put(u,{params:{include:go(bo,i)},body:e,headers:c,timeout:a})},t}();const Eo=Co,Io=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,E.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return"".concat(t.id).localeCompare("".concat(e.id))})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}();var Oo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Po=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return Oo(e,t),e}(m),To=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new nr(Xn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new Io;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new Po(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,E.isEqual)((0,E.map)(t,"code"),(0,E.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,E.isEqual)((0,E.map)(t,"code"),(0,E.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,o=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:o}},t}();function Ao(t){return Ao="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ao(t)}const xo=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return Tr.c.create((function(n){n.next((0,a.VP)(dt.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,a.VP)(dt.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,a.fQ)(dt.LoadConfigFailed,t))}))}))},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":Ao(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadConfig",null),t}();var ko=function(){return ko=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new wo(t);throw t}))},t}();const Mo=Ro;var jo=n(45893);function No(t){return No="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},No(t)}function Do(t){var e=t;return"object"===No(e)&&"object"===No(e.payload)&&"string"==typeof e.payload.token}var Lo=function(){return Lo=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadFormFields",null),t}();const Go=Vo;var Ho=function(){return Ho=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&ui(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([pi],t.prototype,"_handleMessage",null),t}();const vi=yi;var mi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const gi=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return mi(e,t),e}(m);var bi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const _i=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return bi(e,t),e}(m);var wi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Si=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return wi(e,t),e}(m);var Ci=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))},Ei=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!u?a:"".concat(a," ").concat("/"," ").concat(u)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const Na=ja;var Da=n(35647);const La=function(){function t(){}return t.prototype.format=function(t){var e=(0,Da.number)(t).card;if(!e)return t;var n=(0,E.max)((0,Da.creditCardType)(t).map((function(t){return(0,E.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,Da.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();n(54232);var za=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new nr(Xn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,E.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"===eu(t)&&"address"in t},t}();const iu=ou;var au=function(){return au=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([tc],t)}();function rc(t){return rc="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rc(t)}const oc=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":rc(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([tc],t)}();function ic(t){return{errors:new nc(t),statuses:new oc(t)}}function ac(t){return ac="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ac(t)}var uc=function(){return uc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([pi],t)}();const sc=cc;var lc=function(){return lc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t}function $c(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function Qc(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var Zc=function(){return Zc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?o:i[0]:"en_us"}function hs(t){return hs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hs(t)}const ys=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new ii('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new nr(Xn.MissingPaymentMethod);var o={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ds(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(o)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,o=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new nr(Xn.MissingPaymentMethod);if(!o)throw new ii("Unable to retrieve store configuration");var i=document.createElement("input");if(i.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",u=r.initializationData.checkoutId,c=["locale=".concat(ds(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(u)];i.src=["https://".concat(a,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),c.join("&")].join("?")}else i.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(i),i.addEventListener("click",this._handleWalletButtonClick),i},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new nr(Xn.MissingCheckout);if(!n)throw new nr(Xn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat("cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new Ri(Pi.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":hs(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([pi],t.prototype,"_handleWalletButtonClick",null),t}();var vs=function(){return vs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===bs()&&Is.warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var u=a[0];if(u&&u.token)return u.token;if(this._useFallback){var c=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const Ps=Os;var Ts=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const As=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Ts(e,t),e}(c);var xs,ks=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(xs||(xs={}));const Rs=function(t){function e(e){var n=t.call(this,function(t){switch(t){case xs.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case xs.MissingCart:return"Unable to proceed because cart data is unavailable.";case xs.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case xs.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case xs.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case xs.MissingCheckoutConfig:case xs.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case xs.MissingOrder:return"Unable to proceed because order data is unavailable.";case xs.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case xs.MissingPayment:return"Unable to proceed because payment data is unavailable.";case xs.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case xs.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case xs.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return ks(e,t),e}(c);function Ms(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,E.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function js(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Ns,Ds=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Ns||(Ns={}));const Ls=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Ns.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Ns.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Ns.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Ns.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return Ds(e,t),e}(c);var zs,Us,Fs,Bs,qs,Vs,Gs={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(zs||(zs={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(Us||(Us={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(Fs||(Fs={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(Bs||(Bs={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(qs||(qs={})),function(t){t.C0001="C0001"}(Vs||(Vs={}));var Hs=function(){return Hs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:s,merchantCapabilities:p,supportedNetworks:d,lineItems:[],total:h?{label:u,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:u,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(h)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var v=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return v.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=v}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return Dl(r,void 0,void 0,(function(){var r;return Ll(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return Dl(r,void 0,void 0,(function(){var t;return Ll(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Al;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return Dl(this,void 0,void 0,(function(){var n,r;return Ll(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Rs(xs.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new tl;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Rs(xs.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return Dl(this,void 0,void 0,(function(){var o,i,a,u,c,s,l,f,p,d,h,y;return Ll(this,(function(v){switch(v.label){case 0:o=this._transformContactToAddress(n.shippingContact),v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return v.sent(),[3,4];case 3:throw v.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,u=i.getCheckoutOrThrow(),c=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,s=u.consignments[0].availableShippingOptions,l=null==s?void 0:s.find((function(t){return t.id===c})),f=null==s?void 0:s.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:"".concat(l.cost.toFixed(a)),detail:l.additionalDescription,identifier:l.id}]:[],f&&zl(zl([],f.filter((function(t){return t.isRecommended})),!0),f.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(s instanceof Array))throw new Error("Shipping options not available.");if(0===s.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(u.grandTotal.toFixed(a))},[]),[2];d=s.find((function(t){return t.isRecommended})),h=d?d.id:s[0].id,y=l?l.id:h,v.label=5;case 5:return v.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return v.sent(),[3,8];case 7:throw v.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),u=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(u.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(u,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return Dl(this,void 0,void 0,(function(){var r,o,i,a;return Ll(this,(function(u){switch(u.label){case 0:r=n.shippingMethod.identifier,u.label=1;case 1:return u.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return u.sent(),[3,4];case 3:throw u.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return Dl(this,void 0,void 0,(function(){return Ll(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return Dl(this,void 0,void 0,(function(){var n;return Ll(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return Dl(this,void 0,void 0,(function(){var o,i,a,u,c,s,l,f,p,d,h,y,v;return Ll(this,(function(m){switch(m.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,u=o.shippingContact,c=this._paymentIntegrationService.getState(),s=c.getCartOrThrow(),l=s.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==xl.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:f=m.sent(),m.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:f,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},d=this._transformContactToAddress(a),h=this._transformContactToAddress(u),y=null==u?void 0:u.emailAddress,v=(null==u?void 0:u.phoneNumber)||"",m.label=3;case 3:return m.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Nl(Nl({},d),{email:y,phone:v}))];case 4:return m.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,6];case 5:m.sent(),m.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return m.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return m.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw m.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return Dl(this,void 0,void 0,(function(){return Ll(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return Dl(this,void 0,void 0,(function(){var t,e;return Ll(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(xl.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(xl.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const Fl=Ul,Bl=Js((function(t){var e=t.getState().getHost;return new Fl((0,o.createRequestSender)({host:e()}),t,new Rl,new Pl(new Sc((0,Hr.vQ)(),window)))}),[{id:"applepay"}]);var ql=n(80652),Vl=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Gl=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return Vl(e,t),e}(c);var Hl,Yl,Wl;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(Hl||(Hl={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(Yl||(Yl={})),function(t){t.Pill="pill",t.Rect="rect"}(Wl||(Wl={}));var Kl=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,u,c,s,l,f,p,d;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const uf=af,cf=Js((function(t){var e=window,n=new Pl(new Sc((0,Hr.vQ)(),e));return new uf(t,(0,i.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function sf(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function lf(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([pi],t)}();var wf,Sf,Cf,Ef,If,Of,Pf,Tf;function Af(t){return t in Of}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(wf||(wf={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(Sf||(Sf={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Cf||(Cf={})),function(t){t.pill="pill",t.rect="rect"}(Ef||(Ef={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(If||(If={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(Of||(Of={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(Pf||(Pf={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Tf||(Tf={}));var xf=function(){return xf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0))},t.prototype._mapToAddressRequestBody=function(t,e,n){var r=t.name,o=t.address1,i=t.address2,a=t.address3,u=t.locality,c=t.administrativeArea,s=t.countryCode,l=t.postalCode,f=t.phoneNumber,p=this._getFirstAndLastName(r);return{firstName:p[0],lastName:p[1],company:e,address1:o,address2:"".concat(i," ").concat(a).trim(),city:u||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:s,postalCode:l,phone:f||n,customFields:[]}},t.prototype._getFirstAndLastName=function(t){var e=t.split(" ");return 1===e.length?[t,""]:[e.slice(0,-1).join(" "),e[e.length-1]]},t.prototype._getCurrencyCodeOrThrow=function(){return js(this._currencyCode,(function(){return new As('Unable to initialize payment because "options.currencyCode" argument is not provided.')}))},t.prototype._getGooglePayShippingOption=function(t){var e,n=t.id,r=t.cost;return{id:n,label:t.description,description:(null===(e=this._currencyService)||void 0===e?void 0:e.toCustomerCurrency(r))||r}},t}();const jf=Mf;var Nf=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Df=function(){return Df=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":R.length>0?R:void 0,commit:_,components:dp(dp(["buttons","hosted-fields","messages","payment-fields","legal"],j,!0),E,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=lp(lp({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const yp=hp,vp=Js((function(t){return new Kf(t,new Xf(rp(),new sp(t,new yp((0,Hr.vQ)())),(0,o.createRequestSender)(),(0,i.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]),mp=Js((function(t){var e=(0,o.createRequestSender)();return new Kf(t,new Xf(rp(),new jf("adyen",t),e,(0,i.createFormPoster)()))}),[{id:"googlepayadyenv2"}]),gp=Js((function(t){var e=(0,o.createRequestSender)();return new Kf(t,new Xf(rp(),new jf("adyen",t),e,(0,i.createFormPoster)()))}),[{id:"googlepayadyenv3"}]);var bp=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),_p=function(t){function e(e){return t.call(this,"authorizenet",e)||this}return bp(e,t),e.prototype.mapToExternalCheckoutData=function(e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const wd=_d;var Sd=function(){return Sd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?j:void 0,"disable-funding":M.length>0?M:void 0,commit:_,components:xd(xd(["buttons","hosted-fields","payment-fields","legal"],k,!0),R,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Pd(Pd({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Rd=kd,Md=function(t){var e=t.getState().getHost;return new wd((0,i.createFormPoster)(),t,new Od((0,o.createRequestSender)({host:e()})),new Rd((0,Hr.vQ)()))};var jd=function(){return jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=l.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Nd(this,void 0,void 0,(function(){var e,n,r;return Dd(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Nd(this,void 0,void 0,(function(){var e,n;return Dd(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const zd=Ld,Ud=Js((function(t){return new zd(t,Md(t))}),[{id:"paypalcommerce"}]);var Fd=function(){return Fd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?d:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},c&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":u,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Rs(xs.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,u=n.buyerCountry;return{options:Fd({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":u}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Fd(Fd({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Gd=Vd,Hd=function(t){var e=t.styles,n={};return e.color&&(n.color=e.color),e.layout&&(n.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(n.logo={},e["logo-type"]&&(n.logo.type=e["logo-type"]),e["logo-position"]&&(n.logo.position=e["logo-position"])),e.ratio&&(n.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(n.text={},e["text-color"]&&(n.text.color=e["text-color"]),e["text-size"]&&(n.text.size=+e["text-size"])),n};var Yd=function(){return Yd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=l.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Wd(this,void 0,void 0,(function(){var e,n,r;return Kd(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Wd(this,void 0,void 0,(function(){var e,n;return Kd(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?Hd(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const Qd=$d,Zd=Js((function(t){return new Qd(t,Md(t),new Gd((0,Hr.Hb)()))}),[{id:"paypalcommercecredit"}]);var Jd=function(){return Jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1](()=>{var t={22723:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(95757)),i=l(n(61461)),a=l(n(20501)),u=l(n(22682)),c=l(n(33697)),s=l(n(98610));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,e.default={host:""}},88604:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},55739:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(88604),o=n(40816),i={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:o.GET};e.default=i},40816:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},71249:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(88477),n(14718),n(57188),n(62342),n(25226),n(13521),n(35157),n(25766),n(53618),n(11062),n(948),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=(o=n(95757))&&o.__esModule?o:{default:o},a=n(88604),u=n(30390);function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,u.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,o=t.statusText,i="response"in t?t.response:t.responseText;return i&&(0,u.includes)(n,a.APPLICATION_JSON)&&(i=JSON.parse(i)),{data:i,headers:e,status:r,statusText:o}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,i.default)({},t,function(t,e,n){return(e=l(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&s(e.prototype,n),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},24475:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(65778)),i=l(n(95757)),a=n(40816),u=l(n(55739)),c=l(n(71249)),s=l(n(24475));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n=200&&t.status<300}}])&&p(e.prototype,n),r&&p(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},36421:(t,e,n)=>{"use strict";n(47818),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},30390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return f.default}});var r=p(n(36421)),o=p(n(40570)),i=p(n(67522)),a=p(n(67150)),u=p(n(59731)),c=p(n(41207)),s=p(n(29503)),l=p(n(50377)),f=p(n(31887));function p(t){return t&&t.__esModule?t:{default:t}}},45212:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},46885:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,o.default)(t)};var r=i(n(45212)),o=i(n(40570));function i(t){return t&&t.__esModule?t:{default:t}}},40570:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},67522:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===o(t)&&!Array.isArray(t)}},67150:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(46885)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},59731:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(40570)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},41207:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,o.default)(t)?Object.keys(t).reduce((function(n,r){var o=t[r];return e(o)||(n[r]=o),n}),{}):t};var r,o=(r=n(67522))&&r.__esModule?r:{default:r}},29503:(t,e,n)=>{"use strict";n(8933),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},50377:(t,e,n)=>{"use strict";n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},31887:(t,e,n)=>{"use strict";n(25226),n(69204),n(13521),n(88315),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},34936:(t,e,n)=>{"use strict";e.U=function(t){return o.default.create(t)};var r,o=(r=n(22723))&&r.__esModule?r:{default:r}},22682:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=u(n(84916)),i=u(n(39835)),a=u(n(76473));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(74152),i=n(92299),a=c(n(87730)),u=c(n(76473));function c(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e,n){return(e=c(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=f(n(95757)),i=n(30390),a=f(n(77140)),u=f(n(84094)),c=f(n(65245)),s=f(n(69465)),l=f(n(27231));function f(t){return t&&t.__esModule?t:{default:t}}function p(t){return p="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},p(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE_ACCELERATED_CHECKOUT=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.BRAINTREE_ACCELERATED_CHECKOUT="braintreeacceleratedcheckout",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT="paypalcommerceacceleratedcheckout",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},69465:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(6073),i=n(34526);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},20501:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=s(n(84916)),i=n(92299),a=s(n(18581)),u=s(n(46833)),c=s(n(76473));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},46833:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=n(6073);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=s(n(64003)),a=s(n(85195)),u=s(n(67093)),c=s(n(16620));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=u(n(95757)),i=n(30390),a=u(n(69465));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=s(n(72052)),a=s(n(33018)),u=s(n(88124)),c=s(n(86883));function s(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=n(30390),a=(o=n(69465))&&o.__esModule?o:{default:o};function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=c(n(84916)),i=n(40816),a=c(n(93684)),u=n(91486);function c(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";n(80404),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,i,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},u=a.providerName,c=a.defaultInstrument,s=(0,r.omitNil)({name:u});return(0,r.omitNil)({provider:s,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,i=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:i})),billing_address:o(a.billingAddress),default_instrument:c})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return o(t)}))}):(0,r.omitNil)({shipping_address:o(t.shippingAddress)})};var r=n(30390);function o(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:o})}},2467:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function(t,e){var n=(e||{}).equalityCheck,i=void 0===n?o:n;return function(e,n){return Object.keys(t).reduce((function(o,a){var u,c=t[a],s=e?e[a]:void 0,l=c(s,n);return i(s,l)&&o?o:r.assign({},o,((u={})[a]=l,u))}),e||{})}}},19492:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(44396),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(96150);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(45550);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},o.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},69199:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2467),o=n(56498);e.default=function(t,e,n){return"function"==typeof t?new o.default(t,e,n):new o.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},69776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(49997);e.default=function(t,e,n){return r.__assign({},o.default(t,e,n),{error:!0})}},56498:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(87218),u=n(57532),c=n(96150),s=n(45926),l=n(2557),f=n(12079),p=n(64472),d=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=o.__assign({actionTransformer:f.default,equalityCheck:c,shouldWarnMutation:!0,stateTransformer:p.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(u.mergeMap((function(t){return t.pipe(u.concatMap((function(t){return t})))})),u.filter((function(t){return!!t.type})),u.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),u.distinctUntilChanged((function(t,e){var n=t.state,o=e.state;return r._options.equalityCheck(n,o)})),u.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return l.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],o=1;o0&&(c=c.pipe(u.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),i&&!1===i.initial&&(c=c.pipe(u.skip(1)));var s=[c.subscribe(t),this._notification$.subscribe(t)];return function(){return s.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):s.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,o){var c=n._getDispatchError(e.queueId),s=n._options.actionTransformer(a.from(t).pipe(u.map((function(t){return e.queueId?i.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(s).pipe(u.map((function(t,e){return 0===e&&c.pipe(u.first()).subscribe(o),t.error&&o(t.payload),t})),u.catchError((function(t){return o(t instanceof Error?t:t.payload),a.of(t)})),u.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=d},45926:(t,e,n)=>{"use strict";n(80404),n(56949),n(32194),n(38085),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function t(e,n){try{var i=n||{},a=i.equalityCheck,u=void 0===a?o:a,c=i.previousValue,s=void 0===c?null:c;return u(e,s)&&Object.isFrozen(s)?s:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:u,previousValue:Array.isArray(s)?s[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:u,previousValue:s&&s.hasOwnProperty(r)?s[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},99840:(t,e,n)=>{"use strict";n(56498).default;var r=n(2467);e.HY=r.default;var o=n(19492);e.om=o.default;var i=n(49997);e.VP=i.default;var a=n(69199);e.iN=a.default;var u=n(69776);e.fQ=u.default;var c=n(45926);e.ol=c.default},2557:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},12079:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},64472:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},83736:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>w,__asyncGenerator:()=>_,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>f,__classPrivateFieldGet:()=>O,__classPrivateFieldSet:()=>P,__createBinding:()=>d,__decorate:()=>c,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>s,__read:()=>v,__rest:()=>u,__spread:()=>m,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(i=t[c])&&(u=(a<3?i(u):a>3?i(e,n,u):i(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function s(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function f(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function m(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(c,s):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function c(t){u("next",t)}function s(t){u("throw",t)}function l(t,e){t(e),i.shift(),i.length&&u(i[0][0],i[0][1])}}function w(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function O(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function P(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},21887:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(60834),o=n(33788);e.default=function(t){var e=new r.default;return new o.default(e,t)}},60834:(t,e,n)=>{"use strict";n(21894),n(44594),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,o=document.createElement("form");return o.style.display="none",o.setAttribute("action",t),o.setAttribute("method","POST"),o.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];o.appendChild(r._createInput(n,t))})),o},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},33788:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(12789),o=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var o=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(o),o.submit()},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!(0,r.isAbsoluteUrl)(t)?(0,r.joinPaths)(this._options.host,t):t},t}();e.default=o},74152:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FormPoster=e.createFormPoster=void 0;var r=n(21887);Object.defineProperty(e,"createFormPoster",{enumerable:!0,get:function(){return r.default}});var o=n(33788);Object.defineProperty(e,"FormPoster",{enumerable:!0,get:function(){return o.default}})},12789:(t,e,n)=>{"use strict";n(98556),n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.joinPaths=e.isAbsoluteUrl=void 0,e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return"".concat((n=t,n.replace(/\/$/,"")),"/").concat(function(t){return t.replace(/^\//,"")}(e));var n}},89998:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},26879:(t,e,n)=>{"use strict";n(47818),n(80404),n(44396),n(67068),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=n(45550),i=r.__importDefault(n(96150)),a=n(89998),u=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:i.default,maxSize:0,onExpire:o.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(71652);e.Bj=r.default,e.B4=r.memoizeOne},71652:(t,e,n)=>{"use strict";n(14718),n(20363),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=r.__importDefault(n(59745)),i=r.__importDefault(n(96150)),a=r.__importDefault(n(26879));function u(t,e){var n=r.__assign({maxSize:0,isEqual:i.default},e),u=n.maxSize,c=n.isEqual,s=new Map,l=new a.default({isEqual:c,maxSize:u,onExpire:function(t){return s.delete(t)}}),f=o.default(t,(function(){for(var t=[],e=0;e{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>w,__asyncGenerator:()=>_,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>f,__classPrivateFieldGet:()=>O,__classPrivateFieldSet:()=>P,__createBinding:()=>d,__decorate:()=>c,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>s,__read:()=>v,__rest:()=>u,__spread:()=>m,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;c--)(i=t[c])&&(u=(a<3?i(u):a>3?i(e,n,u):i(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function s(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function f(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function m(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(c,s):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function c(t){u("next",t)}function s(t){u("throw",t)}function l(t,e){t(e),i.shift(),i.length&&u(i[0][0],i[0][1])}}function w(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function O(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function P(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},78163:(t,e,n)=>{"use strict";n.d(e,{g:()=>o}),n(21894);var r=n(43419),o=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.As(e)},t}()},60931:(t,e,n)=>{"use strict";n.d(e,{A:()=>u});var r=n(77650),o=n(39649),i=n(30187),a=n(71844);function u(t){return new a.A(new i.A,new o.A,r,t)}},33767:(t,e,n)=>{"use strict";n.d(e,{A:()=>o});var r=n(85466);function o(t){return new r.A(t)}},9285:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>i.A,Timeout:()=>a.A,createRequestSender:()=>r.A,createTimeout:()=>o.A});var r=n(60931),o=n(33767),i=n(71844),a=n(85466)},66029:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947)},39649:(t,e,n)=>{"use strict";n.d(e,{A:()=>u}),n(57188),n(53618),n(11062),n(948);var r=n(31355),o=n(38780),i=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const u=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(i.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,o.A)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&i.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,o=e.split(":"),i=(o.shift()||"").trim();return i?(0,r.Cl)((0,r.Cl)({},t),((n={})[i.toLowerCase()]=o.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},30187:(t,e,n)=>{"use strict";n.d(e,{A:()=>o}),n(14266),n(21894),n(44594);var r=n(43419);const o=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.As(e,{encode:n}):t},t}()},71844:(t,e,n)=>{"use strict";n.d(e,{A:()=>s}),n(13521),n(67536),n(84090),n(88315),n(95743),n(53618),n(11062);var r=n(31355),o=n(40117),i=n.n(o),a=n(78163),u=n(66029),c=n(85466);const s=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.g}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),o=this._getCachedRequest(t,r);if(o)return Promise.resolve(o);var i=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,o){var a=function(){var a=n._payloadTransformer.toResponse(i);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):o(a)};i.onload=a,i.onerror=a,i.onabort=a,i.ontimeout=a,r.timeout instanceof c.A&&(r.timeout.onComplete((function(){return i.abort()})),r.timeout.start()),(0,u.A)(r.timeout)&&r.timeout.then((function(){return i.abort()})),i.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&this._isLocalRequest(t)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),i()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t.prototype._isLocalRequest=function(t){return!!t.match(new RegExp("^(https?:)?//"+window.location.hostname))||!t.match(new RegExp("^(https?:)?//"))},t}()},85466:(t,e,n)=>{"use strict";n.d(e,{A:()=>r}),n(13521),n(67536);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},38780:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14266),n(14718),n(57188),n(80404),n(21894),n(13521),n(25766),n(92947)},43419:(t,e,n)=>{"use strict";n(91621),n(27481),n(90105),n(98556),n(14266),n(47818),n(14718),n(57188),n(80404),n(44396),n(18492),n(25226),n(21894),n(13521),n(25766),n(53618),n(11062),n(948),n(44594),n(92947);var r=n(23081),o=n(95757);n(88577);function i(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.As=function(t,e){!1===(e=o({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[i(e,t),"[",r,"]"].join(""):[i(e,t),"[",i(r,t),"]=",i(n,t)].join("")};case"bracket":return function(e,n){return null===n?i(e,t):[i(e,t),"[]=",i(n,t)].join("")};default:return function(e,n){return null===n?i(e,t):[i(e,t),"=",i(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var o=t[r];if(void 0===o)return"";if(null===o)return i(r,e);if(Array.isArray(o)){var a=[];return o.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return i(r,e)+"="+i(o,e)})).filter((function(t){return t.length>0})).join("&"):""}},31355:(t,e,n)=>{"use strict";n.d(e,{Cl:()=>r}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},50961:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(860);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},52904:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(79029);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},54721:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(50961);e.default=function(){return r||(r=o.default()),r}},50808:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(52904);e.default=function(){return r||(r=o.default()),r}},4993:(t,e,n)=>{"use strict";n(860).default;var r=n(50961);e.Hb=r.default;var o=n(54721);e.vQ=o.default,n(79029).default,n(52904).default,n(50808).default},860:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,o){var i=document.createElement("script"),a=e||{},u=a.async,c=void 0!==u&&u,s=a.attributes,l=void 0===s?{}:s;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onreadystatechange=function(){return r()},i.onerror=function(e){delete n._scripts[t],o(e)},i.async=c,i.src=t,document.body.appendChild(i)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var u=document.createElement("link");u.as="script",u.rel=a,u.href=t,u.onload=function(){r()},u.onerror=function(){delete n._preloadedScripts[t],o()},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(o)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},79029:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,o){var i=document.createElement("link"),a=e||{},u=a.prepend,c=void 0!==u&&u,s=a.attributes,l=void 0===s?{}:s;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onerror=function(e){delete n._stylesheets[t],o(e)},i.rel="stylesheet",i.href=t,c&&document.head.children[0]?document.head.insertBefore(i,document.head.children[0]):document.head.appendChild(i)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i,u=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(u)){var c=document.createElement("link");c.as="style",c.rel=a?"prefetch":"preload",c.href=t,c.onload=function(){r()},c.onerror=function(e){delete n._preloadedStylesheets[t],o(e)},document.head.appendChild(c)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(o)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},35647:(t,e,n)=>{"use strict";t.exports={number:n(71990),expirationDate:n(15862),expirationMonth:n(38138),expirationYear:n(62711),cvv:n(2999),postalCode:n(89333),creditCardType:n(30439)}},71990:(t,e,n)=>{"use strict";n(53618);var r=n(7759),o=n(30439);function i(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,u,c,s;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return i(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return i(null,!1,!1);if(0===(n=o(t)).length)return i(null,!1,!1);if(1!==n.length)return i(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return i(a,!1,!1);for(u=a.type===o.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),s=Math.max.apply(null,a.lengths),e.maxLength&&(s=Math.min(e.maxLength,s)),c=0;c{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},15862:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(53618),n(92947);var o=n(15410),i=n(38138),a=n(62711);function u(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,c,s,l;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=o(t);else{if(null===t||"object"!==r(t))return u(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(c=i(n.month),s=a(n.year,e),c.isValid){if(s.isCurrentYear)return u(l=c.isValidForThisYear,l,n.month,n.year);if(s.isValid)return u(!0,!0,n.month,n.year)}return c.isPotentiallyValid&&s.isPotentiallyValid?u(!1,!0,null,null):u(!1,!1,null,null)}},38138:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(17186),n(53618),t.exports=function(t){var e,n,o=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=o)):r(!1,!1)}},62711:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}n(44396),n(25226),n(17186),n(53618),t.exports=function(t,e){var n,o,i,a,u;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(o=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===o?r(!1,t.slice(0,2)===String(n).slice(0,2)):o>4?r(!1,!1):(t=parseInt(t,10),i=Number(String(n).substr(2,2)),2===o?(u=i===t,a=t>=i&&t<=i+e):4===o&&(u=n===t,a=t>=n&&t<=n+e),r(a,a,u))):r(!1,!1)}},11476:(t,e,n)=>{"use strict";n(13521),n(88315),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},7759:(t,e,n)=>{"use strict";n(17186),t.exports=function(t){for(var e,n=0,r=!1,o=t.length-1;o>=0;)e=parseInt(t.charAt(o),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,o--;return n%10==0}},15410:(t,e,n)=>{"use strict";n(57188),n(5360),n(44396),n(25226),n(11062);var r=n(62711),o=n(11476);t.exports=function(t){var e,n,i,a,u;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),o(t)?{month:t[0]||"",year:t.slice(1).join()}:(i=t,n=0===(u=Number(i[0]))?2:u>1||1===u&&Number(i[1])>2?1:1===u?(a=i.substr(1),r(a).isPotentiallyValid?1:2):5===i.length?1:i.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},89333:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(47818),n(80404),n(67068),n(21894),n(44594);var r,o=n(45237),i=n(97458),a=n(40179),u=n(84438),c=n(39187),s={},l={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},f=[l.VISA,l.MASTERCARD,l.AMERICAN_EXPRESS,l.DINERS_CLUB,l.DISCOVER,l.JCB,l.UNIONPAY,l.MAESTRO,l.ELO,l.MIR,l.HIPER,l.HIPERCARD];function p(t){return s[t]||o[t]}function d(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function h(t){var e,n=[];return u(t)?0===t.length?r.map((function(t){return i(p(t))})):(r.forEach((function(e){var r=p(e);c(t,r,n)})),(e=a(n))?[e]:n):[]}r=i(f),h.getTypeInfo=function(t){return i(p(t))},h.removeCard=function(t){var e=d(t);r.splice(e,1)},h.addCard=function(t){var e=d(t.type,!0);s[t.type]=t,-1===e&&r.push(t.type)},h.updateCard=function(t,e){var n,r=s[t]||o[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=i(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),s[n.type]=n},h.changeOrder=function(t,e){var n=d(t);r.splice(n,1),r.splice(e,0,t)},h.resetModifications=function(){r=i(f),s={}},h.types=l,t.exports=h},39187:(t,e,n)=>{"use strict";var r=n(97458),o=n(98834);t.exports=function(t,e,n){var i,a,u,c;for(i=0;i=u&&(c.matchStrength=u),n.push(c);break}}},45237:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},97458:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},40179:(t,e,n)=>{"use strict";n(14266),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},98834:(t,e,n)=>{"use strict";n(17186),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,o=t.substr(0,r),i=parseInt(o,10);return e=parseInt(String(e).substr(0,o.length),10),n=parseInt(String(n).substr(0,o.length),10),i>=e&&i<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},88577:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(98556),n(14718),n(57188),n(44396),n(21894),n(13521),n(84090),n(88315),n(25766),n(95743),n(53618),n(92947);var o="%[a-f0-9]{2}",i=new RegExp("("+o+")|([^%]+?)","gi"),a=new RegExp("("+o+")+","gi");function u(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],u(n),u(r))}function c(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(i)||[],n=1;n{"use strict";n(91621);var r=n(62034),o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(t,e,n){var i=e[n];if(null!=i){if(o.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");o.call(t,n)&&r(i)?t[n]=u(Object(t[n]),e[n]):t[n]=i}}function u(t,e){if(t===e)return t;for(var n in e=Object(e))o.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),u=0;u{"use strict";n(47818),n(21894),t.exports=function(t,e){for(var n={},r=Object.keys(t),o=Array.isArray(e),i=0;i{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947),t.exports=function(t){var e=r(t);return null!==t&&("object"===e||"function"===e)}},77650:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(57188),n(44396),n(13521),n(25766),n(53618),n(11062),n(92947),function(n){var o;if("function"==typeof define&&define.amd&&(define(n),o=!0),"object"===r(e)&&(t.exports=n(),o=!0),!o){var i=window.Cookies,a=window.Cookies=n();a.noConflict=function(){return window.Cookies=i,a}}}((function(){function t(){for(var t=0,e={};t{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(80404),n(67068),n(13521),n(84090),n(88315),n(25766),n(53618),n(92947);var o,i="__lodash_hash_undefined__",a="[object Function]",u="[object GeneratorFunction]",c=/^\[object .+?Constructor\]$/,s="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,l="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,f=s||l||Function("return this")(),p=Array.prototype,d=Function.prototype,h=Object.prototype,y=f["__core-js_shared__"],v=(o=/[^.]+$/.exec(y&&y.keys&&y.keys.IE_PROTO||""))?"Symbol(src)_1."+o:"",m=d.toString,g=h.hasOwnProperty,b=h.toString,_=RegExp("^"+m.call(g).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),w=p.splice,S=A(f,"Map"),C=A(Object,"create");function E(t){var e=-1,n=t?t.length:0;for(this.clear();++e-1},I.prototype.set=function(t,e){var n=this.__data__,r=P(n,t);return r<0?n.push([t,e]):n[r][1]=e,this},O.prototype.clear=function(){this.__data__={hash:new E,map:new(S||I),string:new E}},O.prototype.delete=function(t){return T(this,t).delete(t)},O.prototype.get=function(t){return T(this,t).get(t)},O.prototype.has=function(t){return T(this,t).has(t)},O.prototype.set=function(t,e){return T(this,t).set(t,e),this},x.Cache=O,t.exports=x},40117:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(91621),n(27481),n(90105),n(14718),n(80404),n(44396),n(67068),n(46977),n(13521),n(84090),n(88315),n(25766),n(53618),n(92947);var o="__lodash_hash_undefined__",i=9007199254740991,a="[object Arguments]",u="[object AsyncFunction]",c="[object Function]",s="[object GeneratorFunction]",l="[object Null]",f="[object Object]",p="[object Proxy]",d="[object Undefined]",h=/^\[object .+?Constructor\]$/,y=/^(?:0|[1-9]\d*)$/,v={};v["[object Float32Array]"]=v["[object Float64Array]"]=v["[object Int8Array]"]=v["[object Int16Array]"]=v["[object Int32Array]"]=v["[object Uint8Array]"]=v["[object Uint8ClampedArray]"]=v["[object Uint16Array]"]=v["[object Uint32Array]"]=!0,v[a]=v["[object Array]"]=v["[object ArrayBuffer]"]=v["[object Boolean]"]=v["[object DataView]"]=v["[object Date]"]=v["[object Error]"]=v[c]=v["[object Map]"]=v["[object Number]"]=v[f]=v["[object RegExp]"]=v["[object Set]"]=v["[object String]"]=v["[object WeakMap]"]=!1;var m,g,b,_="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,w="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,S=_||w||Function("return this")(),C="object"==r(e)&&e&&!e.nodeType&&e,E=C&&"object"==r(t)&&t&&!t.nodeType&&t,I=E&&E.exports===C,O=I&&_.process,P=function(){try{return E&&E.require&&E.require("util").types||O&&O.binding&&O.binding("util")}catch(t){}}(),T=P&&P.isTypedArray,A=Array.prototype,x=Function.prototype,k=Object.prototype,R=S["__core-js_shared__"],M=x.toString,j=k.hasOwnProperty,N=(m=/[^.]+$/.exec(R&&R.keys&&R.keys.IE_PROTO||""))?"Symbol(src)_1."+m:"",D=k.toString,L=M.call(Object),z=RegExp("^"+M.call(j).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=I?S.Buffer:void 0,F=S.Symbol,B=S.Uint8Array,q=(U&&U.allocUnsafe,g=Object.getPrototypeOf,b=Object,function(t){return g(b(t))}),V=Object.create,G=k.propertyIsEnumerable,H=A.splice,Y=F?F.toStringTag:void 0,W=function(){try{var t=dt(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),K=U?U.isBuffer:void 0,$=Math.max,Q=Date.now,Z=dt(S,"Map"),J=dt(Object,"create"),X=function(){function t(){}return function(e){if(!It(e))return{};if(V)return V(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();function tt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e-1},et.prototype.set=function(t,e){var n=this.__data__,r=at(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},nt.prototype.clear=function(){this.size=0,this.__data__={hash:new tt,map:new(Z||et),string:new tt}},nt.prototype.delete=function(t){var e=pt(this,t).delete(t);return this.size-=e?1:0,e},nt.prototype.get=function(t){return pt(this,t).get(t)},nt.prototype.has=function(t){return pt(this,t).has(t)},nt.prototype.set=function(t,e){var n=pt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},rt.prototype.clear=function(){this.__data__=new et,this.size=0},rt.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},rt.prototype.get=function(t){return this.__data__.get(t)},rt.prototype.has=function(t){return this.__data__.has(t)},rt.prototype.set=function(t,e){var n=this.__data__;if(n instanceof et){var r=n.__data__;if(!Z||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new nt(r)}return n.set(t,e),this.size=n.size,this};function ct(t){return null==t?void 0===t?d:l:Y&&Y in Object(t)?function(t){var e=j.call(t,Y),n=t[Y];try{t[Y]=void 0;var r=!0}catch(t){}var o=D.call(t);return r&&(e?t[Y]=n:delete t[Y]),o}(t):function(t){return D.call(t)}(t)}function st(t){return Ot(t)&&ct(t)==a}function lt(t,e,n,r,o){t!==e&&function(t,e,n){for(var r=-1,o=Object(t),i=n(t),a=i.length;a--;){var u=i[++r];if(!1===e(o[u],u,o))break}}(e,(function(i,a){if(o||(o=new rt),It(i))!function(t,e,n,r,o,i,a){var u=vt(t,n),c=vt(e,n),s=a.get(c);if(s)ot(t,n,s);else{var l,p,d,h,y,v=i?i(u,c,n+"",t,e,a):void 0,m=void 0===v;if(m){var g=_t(c),b=!g&&St(c),_=!g&&!b&&Pt(c);v=c,g||b||_?_t(u)?v=u:Ot(y=u)&&wt(y)?v=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(ft);function gt(t,e){return t===e||t!=t&&e!=e}var bt=st(function(){return arguments}())?st:function(t){return Ot(t)&&j.call(t,"callee")&&!G.call(t,"callee")},_t=Array.isArray;function wt(t){return null!=t&&Et(t.length)&&!Ct(t)}var St=K||function(){return!1};function Ct(t){if(!It(t))return!1;var e=ct(t);return e==c||e==s||e==u||e==p}function Et(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=i}function It(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function Ot(t){return null!=t&&"object"==r(t)}var Pt=T?function(t){return function(e){return t(e)}}(T):function(t){return Ot(t)&&Et(t.length)&&!!v[ct(t)]};function Tt(t){return wt(t)?function(t,e){var n=_t(t),r=!n&&bt(t),o=!n&&!r&&St(t),i=!n&&!r&&!o&&Pt(t),a=n||r||o||i,u=a?function(t,e){for(var n=-1,r=Array(t);++n1?e[o-1]:void 0,a=o>2?e[2]:void 0;for(i=At.length>3&&"function"==typeof i?(o--,i):void 0,a&&function(t,e,n){if(!It(n))return!1;var o=r(e);return!!("number"==o?wt(n)&&ht(e,n.length):"string"==o&&e in n)&>(n[e],t)}(e[0],e[1],a)&&(i=o<3?void 0:i,o=1),t=Object(t);++n"']/g,W=RegExp(H.source),K=RegExp(Y.source),$=/<%-([\s\S]+?)%>/g,Q=/<%([\s\S]+?)%>/g,Z=/<%=([\s\S]+?)%>/g,J=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,X=/^\w*$/,tt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,et=/[\\^$.*+?()[\]{}|]/g,nt=RegExp(et.source),rt=/^\s+/,ot=/\s/,it=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,at=/\{\n\/\* \[wrapped with (.+)\] \*/,ut=/,? & /,ct=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,st=/[()=,{}\[\]\/\s]/,lt=/\\(\\)?/g,ft=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,pt=/\w*$/,dt=/^[-+]0x[0-9a-f]+$/i,ht=/^0b[01]+$/i,yt=/^\[object .+?Constructor\]$/,vt=/^0o[0-7]+$/i,mt=/^(?:0|[1-9]\d*)$/,gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,bt=/($^)/,_t=/['\n\r\u2028\u2029\\]/g,wt="\\ud800-\\udfff",St="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ct="\\u2700-\\u27bf",Et="a-z\\xdf-\\xf6\\xf8-\\xff",It="A-Z\\xc0-\\xd6\\xd8-\\xde",Ot="\\ufe0e\\ufe0f",Pt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Tt="["+wt+"]",At="["+Pt+"]",xt="["+St+"]",kt="\\d+",Rt="["+Ct+"]",Mt="["+Et+"]",jt="[^"+wt+Pt+kt+Ct+Et+It+"]",Nt="\\ud83c[\\udffb-\\udfff]",Dt="[^"+wt+"]",Lt="(?:\\ud83c[\\udde6-\\uddff]){2}",zt="[\\ud800-\\udbff][\\udc00-\\udfff]",Ut="["+It+"]",Ft="\\u200d",Bt="(?:"+Mt+"|"+jt+")",qt="(?:"+Ut+"|"+jt+")",Vt="(?:['’](?:d|ll|m|re|s|t|ve))?",Gt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ht="(?:"+xt+"|"+Nt+")?",Yt="["+Ot+"]?",Wt=Yt+Ht+"(?:"+Ft+"(?:"+[Dt,Lt,zt].join("|")+")"+Yt+Ht+")*",Kt="(?:"+[Rt,Lt,zt].join("|")+")"+Wt,$t="(?:"+[Dt+xt+"?",xt,Lt,zt,Tt].join("|")+")",Qt=RegExp("['’]","g"),Zt=RegExp(xt,"g"),Jt=RegExp(Nt+"(?="+Nt+")|"+$t+Wt,"g"),Xt=RegExp([Ut+"?"+Mt+"+"+Vt+"(?="+[At,Ut,"$"].join("|")+")",qt+"+"+Gt+"(?="+[At,Ut+Bt,"$"].join("|")+")",Ut+"?"+Bt+"+"+Vt,Ut+"+"+Gt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",kt,Kt].join("|"),"g"),te=RegExp("["+Ft+wt+St+Ot+"]"),ee=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ne=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],re=-1,oe={};oe[M]=oe[j]=oe[N]=oe[D]=oe[L]=oe[z]=oe[U]=oe[F]=oe[B]=!0,oe[y]=oe[v]=oe[k]=oe[m]=oe[R]=oe[g]=oe[b]=oe[_]=oe[S]=oe[C]=oe[E]=oe[O]=oe[P]=oe[T]=oe[x]=!1;var ie={};ie[y]=ie[v]=ie[k]=ie[R]=ie[m]=ie[g]=ie[M]=ie[j]=ie[N]=ie[D]=ie[L]=ie[S]=ie[C]=ie[E]=ie[O]=ie[P]=ie[T]=ie[A]=ie[z]=ie[U]=ie[F]=ie[B]=!0,ie[b]=ie[_]=ie[x]=!1;var ae={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ue=parseFloat,ce=parseInt,se="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,le="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,fe=se||le||Function("return this")(),pe="object"==r(e)&&e&&!e.nodeType&&e,de=pe&&"object"==r(t)&&t&&!t.nodeType&&t,he=de&&de.exports===pe,ye=he&&se.process,ve=function(){try{return de&&de.require&&de.require("util").types||ye&&ye.binding&&ye.binding("util")}catch(t){}}(),me=ve&&ve.isArrayBuffer,ge=ve&&ve.isDate,be=ve&&ve.isMap,_e=ve&&ve.isRegExp,we=ve&&ve.isSet,Se=ve&&ve.isTypedArray;function Ce(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Ee(t,e,n,r){for(var o=-1,i=null==t?0:t.length;++o-1}function xe(t,e,n){for(var r=-1,o=null==t?0:t.length;++r-1;);return n}function Xe(t,e){for(var n=t.length;n--&&Ue(e,t[n],0)>-1;);return n}var tn=Ge({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",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:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),en=Ge({"&":"&","<":"<",">":">",'"':""","'":"'"});function nn(t){return"\\"+ae[t]}function rn(t){return te.test(t)}function on(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function an(t,e){return function(n){return t(e(n))}}function un(t,e){for(var n=-1,r=t.length,o=0,i=[];++n",""":'"',"'":"'"}),hn=function t(e){var n,ot=(e=null==e?fe:hn.defaults(fe.Object(),e,hn.pick(fe,ne))).Array,wt=e.Date,St=e.Error,Ct=e.Function,Et=e.Math,It=e.Object,Ot=e.RegExp,Pt=e.String,Tt=e.TypeError,At=ot.prototype,xt=Ct.prototype,kt=It.prototype,Rt=e["__core-js_shared__"],Mt=xt.toString,jt=kt.hasOwnProperty,Nt=0,Dt=(n=/[^.]+$/.exec(Rt&&Rt.keys&&Rt.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",Lt=kt.toString,zt=Mt.call(It),Ut=fe._,Ft=Ot("^"+Mt.call(jt).replace(et,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bt=he?e.Buffer:o,qt=e.Symbol,Vt=e.Uint8Array,Gt=Bt?Bt.allocUnsafe:o,Ht=an(It.getPrototypeOf,It),Yt=It.create,Wt=kt.propertyIsEnumerable,Kt=At.splice,$t=qt?qt.isConcatSpreadable:o,Jt=qt?qt.iterator:o,te=qt?qt.toStringTag:o,ae=function(){try{var t=li(It,"defineProperty");return t({},"",{}),t}catch(t){}}(),se=e.clearTimeout!==fe.clearTimeout&&e.clearTimeout,le=wt&&wt.now!==fe.Date.now&&wt.now,pe=e.setTimeout!==fe.setTimeout&&e.setTimeout,de=Et.ceil,ye=Et.floor,ve=It.getOwnPropertySymbols,De=Bt?Bt.isBuffer:o,Ge=e.isFinite,yn=At.join,vn=an(It.keys,It),mn=Et.max,gn=Et.min,bn=wt.now,_n=e.parseInt,wn=Et.random,Sn=At.reverse,Cn=li(e,"DataView"),En=li(e,"Map"),In=li(e,"Promise"),On=li(e,"Set"),Pn=li(e,"WeakMap"),Tn=li(It,"create"),An=Pn&&new Pn,xn={},kn=zi(Cn),Rn=zi(En),Mn=zi(In),jn=zi(On),Nn=zi(Pn),Dn=qt?qt.prototype:o,Ln=Dn?Dn.valueOf:o,zn=Dn?Dn.toString:o;function Un(t){if(eu(t)&&!Ga(t)&&!(t instanceof Vn)){if(t instanceof qn)return t;if(jt.call(t,"__wrapped__"))return Ui(t)}return new qn(t)}var Fn=function(){function t(){}return function(e){if(!tu(e))return{};if(Yt)return Yt(e);t.prototype=e;var n=new t;return t.prototype=o,n}}();function Bn(){}function qn(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=o}function Vn(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=d,this.__views__=[]}function Gn(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function ur(t,e,n,r,i,a){var u,c=1&e,s=2&e,l=4&e;if(n&&(u=i?n(t,r,i,a):n(t)),u!==o)return u;if(!tu(t))return t;var f=Ga(t);if(f){if(u=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&jt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!c)return To(t,u)}else{var p=di(t),d=p==_||p==w;if(Ka(t))return So(t,c);if(p==E||p==y||d&&!i){if(u=s||d?{}:yi(t),!c)return s?function(t,e){return Ao(t,pi(t),e)}(t,function(t,e){return t&&Ao(e,Ru(e),t)}(u,t)):function(t,e){return Ao(t,fi(t),e)}(t,rr(u,t))}else{if(!ie[p])return i?t:{};u=function(t,e,n){var r,o=t.constructor;switch(e){case k:return Co(t);case m:case g:return new o(+t);case R:return function(t,e){var n=e?Co(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case M:case j:case N:case D:case L:case z:case U:case F:case B:return Eo(t,n);case S:return new o;case C:case T:return new o(t);case O:return function(t){var e=new t.constructor(t.source,pt.exec(t));return e.lastIndex=t.lastIndex,e}(t);case P:return new o;case A:return r=t,Ln?It(Ln.call(r)):{}}}(t,p,c)}}a||(a=new Kn);var h=a.get(t);if(h)return h;a.set(t,u),au(t)?t.forEach((function(r){u.add(ur(r,e,n,r,t,a))})):nu(t)&&t.forEach((function(r,o){u.set(o,ur(r,e,n,o,t,a))}));var v=f?o:(l?s?ri:ni:s?Ru:ku)(t);return Ie(v||t,(function(r,o){v&&(r=t[o=r]),tr(u,o,ur(r,e,n,o,t,a))})),u}function cr(t,e,n){var r=n.length;if(null==t)return!r;for(t=It(t);r--;){var i=n[r],a=e[i],u=t[i];if(u===o&&!(i in t)||!a(u))return!1}return!0}function sr(t,e,n){if("function"!=typeof t)throw new Tt(i);return Ai((function(){t.apply(o,n)}),e)}function lr(t,e,n,r){var o=-1,i=Ae,a=!0,u=t.length,c=[],s=e.length;if(!u)return c;n&&(e=ke(e,$e(n))),r?(i=xe,a=!1):e.length>=200&&(i=Ze,a=!1,e=new Wn(e));t:for(;++o-1},Hn.prototype.set=function(t,e){var n=this.__data__,r=er(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},Yn.prototype.clear=function(){this.size=0,this.__data__={hash:new Gn,map:new(En||Hn),string:new Gn}},Yn.prototype.delete=function(t){var e=ci(this,t).delete(t);return this.size-=e?1:0,e},Yn.prototype.get=function(t){return ci(this,t).get(t)},Yn.prototype.has=function(t){return ci(this,t).has(t)},Yn.prototype.set=function(t,e){var n=ci(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},Wn.prototype.add=Wn.prototype.push=function(t){return this.__data__.set(t,a),this},Wn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.clear=function(){this.__data__=new Hn,this.size=0},Kn.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},Kn.prototype.get=function(t){return this.__data__.get(t)},Kn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Hn){var r=n.__data__;if(!En||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Yn(r)}return n.set(t,e),this.size=n.size,this};var fr=Ro(br),pr=Ro(_r,!0);function dr(t,e){var n=!0;return fr(t,(function(t,r,o){return n=!!e(t,r,o)})),n}function hr(t,e,n){for(var r=-1,i=t.length;++r0&&n(u)?e>1?vr(u,e-1,n,r,o):Re(o,u):r||(o[o.length]=u)}return o}var mr=Mo(),gr=Mo(!0);function br(t,e){return t&&mr(t,e,ku)}function _r(t,e){return t&&gr(t,e,ku)}function wr(t,e){return Te(e,(function(e){return Za(t[e])}))}function Sr(t,e){for(var n=0,r=(e=go(e,t)).length;null!=t&&ne}function Or(t,e){return null!=t&&jt.call(t,e)}function Pr(t,e){return null!=t&&e in It(t)}function Tr(t,e,n){for(var r=n?xe:Ae,i=t[0].length,a=t.length,u=a,c=ot(a),s=1/0,l=[];u--;){var f=t[u];u&&e&&(f=ke(f,$e(e))),s=gn(f.length,s),c[u]=!n&&(e||i>=120&&f.length>=120)?new Wn(u&&f):o}f=t[0];var p=-1,d=c[0];t:for(;++p=u?c:c*("desc"==n[r]?-1:1)}return t.index-e.index}(t,e,n)}));e--;)t[e]=t[e].value;return t}(o)}function Vr(t,e,n){for(var r=-1,o=e.length,i={};++r-1;)u!==t&&Kt.call(u,c,1),Kt.call(t,c,1);return t}function Hr(t,e){for(var n=t?e.length:0,r=n-1;n--;){var o=e[n];if(n==r||o!==i){var i=o;mi(o)?Kt.call(t,o,1):so(t,o)}}return t}function Yr(t,e){return t+ye(wn()*(e-t+1))}function Wr(t,e){var n="";if(!t||e<1||e>f)return n;do{e%2&&(n+=t),(e=ye(e/2))&&(t+=t)}while(e);return n}function Kr(t,e){return xi(Ii(t,e,rc),t+"")}function $r(t){return Qn(Fu(t))}function Qr(t,e){var n=Fu(t);return Mi(n,ar(e,0,n.length))}function Zr(t,e,n,r){if(!tu(t))return t;for(var i=-1,a=(e=go(e,t)).length,u=a-1,c=t;null!=c&&++io?0:o+e),(n=n>o?o:n)<0&&(n+=o),o=e>n?0:n-e>>>0,e>>>=0;for(var i=ot(o);++r>>1,a=t[i];null!==a&&!cu(a)&&(n?a<=e:a=200){var s=e?null:Ko(t);if(s)return cn(s);a=!1,o=Ze,c=new Wn}else c=e?[]:u;t:for(;++r=r?t:eo(t,e,n)}var wo=se||function(t){return fe.clearTimeout(t)};function So(t,e){if(e)return t.slice();var n=t.length,r=Gt?Gt(n):new t.constructor(n);return t.copy(r),r}function Co(t){var e=new t.constructor(t.byteLength);return new Vt(e).set(new Vt(t)),e}function Eo(t,e){var n=e?Co(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Io(t,e){if(t!==e){var n=t!==o,r=null===t,i=t==t,a=cu(t),u=e!==o,c=null===e,s=e==e,l=cu(e);if(!c&&!l&&!a&&t>e||a&&u&&s&&!c&&!l||r&&u&&s||!n&&s||!i)return 1;if(!r&&!a&&!l&&t1?n[i-1]:o,u=i>2?n[2]:o;for(a=t.length>3&&"function"==typeof a?(i--,a):o,u&&gi(n[0],n[1],u)&&(a=i<3?o:a,i=1),e=It(e);++r-1?i[a?e[u]:u]:o}}function zo(t){return ei((function(e){var n=e.length,r=n,a=qn.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new Tt(i);if(a&&!c&&"wrapper"==ii(u))var c=new qn([],!0)}for(r=c?r:n;++r1&&b.reverse(),p&&lc))return!1;var l=a.get(t),f=a.get(e);if(l&&f)return l==e&&f==t;var p=-1,d=!0,h=2&n?new Wn:o;for(a.set(t,e),a.set(e,t);++p-1&&t%1==0&&t1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(it,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return Ie(h,(function(n){var r="_."+n[0];e&n[1]&&!Ae(t,r)&&t.push(r)})),t.sort()}(function(t){var e=t.match(at);return e?e[1].split(ut):[]}(r),n)))}function Ri(t){var e=0,n=0;return function(){var r=bn(),i=16-(r-n);if(n=r,i>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(o,arguments)}}function Mi(t,e){var n=-1,r=t.length,i=r-1;for(e=e===o?r:e;++n1?t[e-1]:o;return n="function"==typeof n?(t.pop(),n):o,ia(t,n)}));function pa(t){var e=Un(t);return e.__chain__=!0,e}function da(t,e){return e(t)}var ha=ei((function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,i=function(e){return ir(e,t)};return!(e>1||this.__actions__.length)&&r instanceof Vn&&mi(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:da,args:[i],thisArg:o}),new qn(r,this.__chain__).thru((function(t){return e&&!t.length&&t.push(o),t}))):this.thru(i)})),ya=xo((function(t,e,n){jt.call(t,n)?++t[n]:or(t,n,1)})),va=Lo(Vi),ma=Lo(Gi);function ga(t,e){return(Ga(t)?Ie:fr)(t,ui(e,3))}function ba(t,e){return(Ga(t)?Oe:pr)(t,ui(e,3))}var _a=xo((function(t,e,n){jt.call(t,n)?t[n].push(e):or(t,n,[e])})),wa=Kr((function(t,e,n){var r=-1,o="function"==typeof e,i=Ya(t)?ot(t.length):[];return fr(t,(function(t){i[++r]=o?Ce(e,t,n):Ar(t,e,n)})),i})),Sa=xo((function(t,e,n){or(t,n,e)}));function Ca(t,e){return(Ga(t)?ke:Lr)(t,ui(e,3))}var Ea=xo((function(t,e,n){t[n?0:1].push(e)}),(function(){return[[],[]]})),Ia=Kr((function(t,e){if(null==t)return[];var n=e.length;return n>1&&gi(t,e[0],e[1])?e=[]:n>2&&gi(e[0],e[1],e[2])&&(e=[e[0]]),qr(t,vr(e,1),[])})),Oa=le||function(){return fe.Date.now()};function Pa(t,e,n){return e=n?o:e,e=t&&null==e?t.length:e,Qo(t,s,o,o,o,o,e)}function Ta(t,e){var n;if("function"!=typeof e)throw new Tt(i);return t=hu(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=o),n}}var Aa=Kr((function(t,e,n){var r=1;if(n.length){var o=un(n,ai(Aa));r|=c}return Qo(t,r,e,n,o)})),xa=Kr((function(t,e,n){var r=3;if(n.length){var o=un(n,ai(xa));r|=c}return Qo(e,r,t,n,o)}));function ka(t,e,n){var r,a,u,c,s,l,f=0,p=!1,d=!1,h=!0;if("function"!=typeof t)throw new Tt(i);function y(e){var n=r,i=a;return r=a=o,f=e,c=t.apply(i,n)}function v(t){var n=t-l;return l===o||n>=e||n<0||d&&t-f>=u}function m(){var t=Oa();if(v(t))return g(t);s=Ai(m,function(t){var n=e-(t-l);return d?gn(n,u-(t-f)):n}(t))}function g(t){return s=o,h&&r?y(t):(r=a=o,c)}function b(){var t=Oa(),n=v(t);if(r=arguments,a=this,l=t,n){if(s===o)return function(t){return f=t,s=Ai(m,e),p?y(t):c}(l);if(d)return wo(s),s=Ai(m,e),y(l)}return s===o&&(s=Ai(m,e)),c}return e=vu(e)||0,tu(n)&&(p=!!n.leading,u=(d="maxWait"in n)?mn(vu(n.maxWait)||0,e):u,h="trailing"in n?!!n.trailing:h),b.cancel=function(){s!==o&&wo(s),f=0,r=l=a=s=o},b.flush=function(){return s===o?c:g(Oa())},b}var Ra=Kr((function(t,e){return sr(t,1,e)})),Ma=Kr((function(t,e,n){return sr(t,vu(e)||0,n)}));function ja(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new Tt(i);var n=function n(){var r=arguments,o=e?e.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=t.apply(this,r);return n.cache=i.set(o,a)||i,a};return n.cache=new(ja.Cache||Yn),n}function Na(t){if("function"!=typeof t)throw new Tt(i);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}ja.Cache=Yn;var Da=bo((function(t,e){var n=(e=1==e.length&&Ga(e[0])?ke(e[0],$e(ui())):ke(vr(e,1),$e(ui()))).length;return Kr((function(r){for(var o=-1,i=gn(r.length,n);++o=e})),Va=xr(function(){return arguments}())?xr:function(t){return eu(t)&&jt.call(t,"callee")&&!Wt.call(t,"callee")},Ga=ot.isArray,Ha=me?$e(me):function(t){return eu(t)&&Er(t)==k};function Ya(t){return null!=t&&Xa(t.length)&&!Za(t)}function Wa(t){return eu(t)&&Ya(t)}var Ka=De||vc,$a=ge?$e(ge):function(t){return eu(t)&&Er(t)==g};function Qa(t){if(!eu(t))return!1;var e=Er(t);return e==b||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!ou(t)}function Za(t){if(!tu(t))return!1;var e=Er(t);return e==_||e==w||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Ja(t){return"number"==typeof t&&t==hu(t)}function Xa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=f}function tu(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function eu(t){return null!=t&&"object"==r(t)}var nu=be?$e(be):function(t){return eu(t)&&di(t)==S};function ru(t){return"number"==typeof t||eu(t)&&Er(t)==C}function ou(t){if(!eu(t)||Er(t)!=E)return!1;var e=Ht(t);if(null===e)return!0;var n=jt.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&Mt.call(n)==zt}var iu=_e?$e(_e):function(t){return eu(t)&&Er(t)==O},au=we?$e(we):function(t){return eu(t)&&di(t)==P};function uu(t){return"string"==typeof t||!Ga(t)&&eu(t)&&Er(t)==T}function cu(t){return"symbol"==r(t)||eu(t)&&Er(t)==A}var su=Se?$e(Se):function(t){return eu(t)&&Xa(t.length)&&!!oe[Er(t)]},lu=Ho(Dr),fu=Ho((function(t,e){return t<=e}));function pu(t){if(!t)return[];if(Ya(t))return uu(t)?fn(t):To(t);if(Jt&&t[Jt])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[Jt]());var e=di(t);return(e==S?on:e==P?cn:Fu)(t)}function du(t){return t?(t=vu(t))===l||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function hu(t){var e=du(t),n=e%1;return e==e?n?e-n:e:0}function yu(t){return t?ar(hu(t),0,d):0}function vu(t){if("number"==typeof t)return t;if(cu(t))return p;if(tu(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=tu(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Ke(t);var n=ht.test(t);return n||vt.test(t)?ce(t.slice(2),n?2:8):dt.test(t)?p:+t}function mu(t){return Ao(t,Ru(t))}function gu(t){return null==t?"":uo(t)}var bu=ko((function(t,e){if(Si(e)||Ya(e))Ao(e,ku(e),t);else for(var n in e)jt.call(e,n)&&tr(t,n,e[n])})),_u=ko((function(t,e){Ao(e,Ru(e),t)})),wu=ko((function(t,e,n,r){Ao(e,Ru(e),t,r)})),Su=ko((function(t,e,n,r){Ao(e,ku(e),t,r)})),Cu=ei(ir),Eu=Kr((function(t,e){t=It(t);var n=-1,r=e.length,i=r>2?e[2]:o;for(i&&gi(e[0],e[1],i)&&(r=1);++n1),e})),Ao(t,ri(t),n),r&&(n=ur(n,7,Xo));for(var o=e.length;o--;)so(n,e[o]);return n})),Du=ei((function(t,e){return null==t?{}:function(t,e){return Vr(t,e,(function(e,n){return Pu(t,n)}))}(t,e)}));function Lu(t,e){if(null==t)return{};var n=ke(ri(t),(function(t){return[t]}));return e=ui(e),Vr(t,n,(function(t,n){return e(t,n[0])}))}var zu=$o(ku),Uu=$o(Ru);function Fu(t){return null==t?[]:Qe(t,ku(t))}var Bu=No((function(t,e,n){return e=e.toLowerCase(),t+(n?qu(e):e)}));function qu(t){return Qu(gu(t).toLowerCase())}function Vu(t){return(t=gu(t))&&t.replace(gt,tn).replace(Zt,"")}var Gu=No((function(t,e,n){return t+(n?"-":"")+e.toLowerCase()})),Hu=No((function(t,e,n){return t+(n?" ":"")+e.toLowerCase()})),Yu=jo("toLowerCase"),Wu=No((function(t,e,n){return t+(n?"_":"")+e.toLowerCase()})),Ku=No((function(t,e,n){return t+(n?" ":"")+Qu(e)})),$u=No((function(t,e,n){return t+(n?" ":"")+e.toUpperCase()})),Qu=jo("toUpperCase");function Zu(t,e,n){return t=gu(t),(e=n?o:e)===o?function(t){return ee.test(t)}(t)?function(t){return t.match(Xt)||[]}(t):function(t){return t.match(ct)||[]}(t):t.match(e)||[]}var Ju=Kr((function(t,e){try{return Ce(t,o,e)}catch(t){return Qa(t)?t:new St(t)}})),Xu=ei((function(t,e){return Ie(e,(function(e){e=Li(e),or(t,e,Aa(t[e],t))})),t}));function tc(t){return function(){return t}}var ec=zo(),nc=zo(!0);function rc(t){return t}function oc(t){return jr("function"==typeof t?t:ur(t,1))}var ic=Kr((function(t,e){return function(n){return Ar(n,t,e)}})),ac=Kr((function(t,e){return function(n){return Ar(t,n,e)}}));function uc(t,e,n){var r=ku(e),o=wr(e,r);null!=n||tu(e)&&(o.length||!r.length)||(n=e,e=t,t=this,o=wr(e,ku(e)));var i=!(tu(n)&&"chain"in n&&!n.chain),a=Za(t);return Ie(o,(function(n){var r=e[n];t[n]=r,a&&(t.prototype[n]=function(){var e=this.__chain__;if(i||e){var n=t(this.__wrapped__);return(n.__actions__=To(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,Re([this.value()],arguments))})})),t}function cc(){}var sc=qo(ke),lc=qo(Pe),fc=qo(Ne);function pc(t){return bi(t)?Ve(Li(t)):function(t){return function(e){return Sr(e,t)}}(t)}var dc=Go(),hc=Go(!0);function yc(){return[]}function vc(){return!1}var mc,gc=Bo((function(t,e){return t+e}),0),bc=Wo("ceil"),_c=Bo((function(t,e){return t/e}),1),wc=Wo("floor"),Sc=Bo((function(t,e){return t*e}),1),Cc=Wo("round"),Ec=Bo((function(t,e){return t-e}),0);return Un.after=function(t,e){if("function"!=typeof e)throw new Tt(i);return t=hu(t),function(){if(--t<1)return e.apply(this,arguments)}},Un.ary=Pa,Un.assign=bu,Un.assignIn=_u,Un.assignInWith=wu,Un.assignWith=Su,Un.at=Cu,Un.before=Ta,Un.bind=Aa,Un.bindAll=Xu,Un.bindKey=xa,Un.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Ga(t)?t:[t]},Un.chain=pa,Un.chunk=function(t,e,n){e=(n?gi(t,e,n):e===o)?1:mn(hu(e),0);var r=null==t?0:t.length;if(!r||e<1)return[];for(var i=0,a=0,u=ot(de(r/e));ii?0:i+n),(r=r===o||r>i?i:hu(r))<0&&(r+=i),r=n>r?0:yu(r);n>>0)?(t=gu(t))&&("string"==typeof e||null!=e&&!iu(e))&&!(e=uo(e))&&rn(t)?_o(fn(t),0,n):t.split(e,n):[]},Un.spread=function(t,e){if("function"!=typeof t)throw new Tt(i);return e=null==e?0:mn(hu(e),0),Kr((function(n){var r=n[e],o=_o(n,0,e);return r&&Re(o,r),Ce(t,this,o)}))},Un.tail=function(t){var e=null==t?0:t.length;return e?eo(t,1,e):[]},Un.take=function(t,e,n){return t&&t.length?eo(t,0,(e=n||e===o?1:hu(e))<0?0:e):[]},Un.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?eo(t,(e=r-(e=n||e===o?1:hu(e)))<0?0:e,r):[]},Un.takeRightWhile=function(t,e){return t&&t.length?fo(t,ui(e,3),!1,!0):[]},Un.takeWhile=function(t,e){return t&&t.length?fo(t,ui(e,3)):[]},Un.tap=function(t,e){return e(t),t},Un.throttle=function(t,e,n){var r=!0,o=!0;if("function"!=typeof t)throw new Tt(i);return tu(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),ka(t,e,{leading:r,maxWait:e,trailing:o})},Un.thru=da,Un.toArray=pu,Un.toPairs=zu,Un.toPairsIn=Uu,Un.toPath=function(t){return Ga(t)?ke(t,Li):cu(t)?[t]:To(Di(gu(t)))},Un.toPlainObject=mu,Un.transform=function(t,e,n){var r=Ga(t),o=r||Ka(t)||su(t);if(e=ui(e,4),null==n){var i=t&&t.constructor;n=o?r?new i:[]:tu(t)&&Za(i)?Fn(Ht(t)):{}}return(o?Ie:br)(t,(function(t,r,o){return e(n,t,r,o)})),n},Un.unary=function(t){return Pa(t,1)},Un.union=ea,Un.unionBy=na,Un.unionWith=ra,Un.uniq=function(t){return t&&t.length?co(t):[]},Un.uniqBy=function(t,e){return t&&t.length?co(t,ui(e,2)):[]},Un.uniqWith=function(t,e){return e="function"==typeof e?e:o,t&&t.length?co(t,o,e):[]},Un.unset=function(t,e){return null==t||so(t,e)},Un.unzip=oa,Un.unzipWith=ia,Un.update=function(t,e,n){return null==t?t:lo(t,e,mo(n))},Un.updateWith=function(t,e,n,r){return r="function"==typeof r?r:o,null==t?t:lo(t,e,mo(n),r)},Un.values=Fu,Un.valuesIn=function(t){return null==t?[]:Qe(t,Ru(t))},Un.without=aa,Un.words=Zu,Un.wrap=function(t,e){return La(mo(e),t)},Un.xor=ua,Un.xorBy=ca,Un.xorWith=sa,Un.zip=la,Un.zipObject=function(t,e){return yo(t||[],e||[],tr)},Un.zipObjectDeep=function(t,e){return yo(t||[],e||[],Zr)},Un.zipWith=fa,Un.entries=zu,Un.entriesIn=Uu,Un.extend=_u,Un.extendWith=wu,uc(Un,Un),Un.add=gc,Un.attempt=Ju,Un.camelCase=Bu,Un.capitalize=qu,Un.ceil=bc,Un.clamp=function(t,e,n){return n===o&&(n=e,e=o),n!==o&&(n=(n=vu(n))==n?n:0),e!==o&&(e=(e=vu(e))==e?e:0),ar(vu(t),e,n)},Un.clone=function(t){return ur(t,4)},Un.cloneDeep=function(t){return ur(t,5)},Un.cloneDeepWith=function(t,e){return ur(t,5,e="function"==typeof e?e:o)},Un.cloneWith=function(t,e){return ur(t,4,e="function"==typeof e?e:o)},Un.conformsTo=function(t,e){return null==e||cr(t,e,ku(e))},Un.deburr=Vu,Un.defaultTo=function(t,e){return null==t||t!=t?e:t},Un.divide=_c,Un.endsWith=function(t,e,n){t=gu(t),e=uo(e);var r=t.length,i=n=n===o?r:ar(hu(n),0,r);return(n-=e.length)>=0&&t.slice(n,i)==e},Un.eq=Fa,Un.escape=function(t){return(t=gu(t))&&K.test(t)?t.replace(Y,en):t},Un.escapeRegExp=function(t){return(t=gu(t))&&nt.test(t)?t.replace(et,"\\$&"):t},Un.every=function(t,e,n){var r=Ga(t)?Pe:dr;return n&&gi(t,e,n)&&(e=o),r(t,ui(e,3))},Un.find=va,Un.findIndex=Vi,Un.findKey=function(t,e){return Le(t,ui(e,3),br)},Un.findLast=ma,Un.findLastIndex=Gi,Un.findLastKey=function(t,e){return Le(t,ui(e,3),_r)},Un.floor=wc,Un.forEach=ga,Un.forEachRight=ba,Un.forIn=function(t,e){return null==t?t:mr(t,ui(e,3),Ru)},Un.forInRight=function(t,e){return null==t?t:gr(t,ui(e,3),Ru)},Un.forOwn=function(t,e){return t&&br(t,ui(e,3))},Un.forOwnRight=function(t,e){return t&&_r(t,ui(e,3))},Un.get=Ou,Un.gt=Ba,Un.gte=qa,Un.has=function(t,e){return null!=t&&hi(t,e,Or)},Un.hasIn=Pu,Un.head=Yi,Un.identity=rc,Un.includes=function(t,e,n,r){t=Ya(t)?t:Fu(t),n=n&&!r?hu(n):0;var o=t.length;return n<0&&(n=mn(o+n,0)),uu(t)?n<=o&&t.indexOf(e,n)>-1:!!o&&Ue(t,e,n)>-1},Un.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=null==n?0:hu(n);return o<0&&(o=mn(r+o,0)),Ue(t,e,o)},Un.inRange=function(t,e,n){return e=du(e),n===o?(n=e,e=0):n=du(n),function(t,e,n){return t>=gn(e,n)&&t=-9007199254740991&&t<=f},Un.isSet=au,Un.isString=uu,Un.isSymbol=cu,Un.isTypedArray=su,Un.isUndefined=function(t){return t===o},Un.isWeakMap=function(t){return eu(t)&&di(t)==x},Un.isWeakSet=function(t){return eu(t)&&"[object WeakSet]"==Er(t)},Un.join=function(t,e){return null==t?"":yn.call(t,e)},Un.kebabCase=Gu,Un.last=Qi,Un.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r;return n!==o&&(i=(i=hu(n))<0?mn(r+i,0):gn(i,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,i):ze(t,Be,i,!0)},Un.lowerCase=Hu,Un.lowerFirst=Yu,Un.lt=lu,Un.lte=fu,Un.max=function(t){return t&&t.length?hr(t,rc,Ir):o},Un.maxBy=function(t,e){return t&&t.length?hr(t,ui(e,2),Ir):o},Un.mean=function(t){return qe(t,rc)},Un.meanBy=function(t,e){return qe(t,ui(e,2))},Un.min=function(t){return t&&t.length?hr(t,rc,Dr):o},Un.minBy=function(t,e){return t&&t.length?hr(t,ui(e,2),Dr):o},Un.stubArray=yc,Un.stubFalse=vc,Un.stubObject=function(){return{}},Un.stubString=function(){return""},Un.stubTrue=function(){return!0},Un.multiply=Sc,Un.nth=function(t,e){return t&&t.length?Br(t,hu(e)):o},Un.noConflict=function(){return fe._===this&&(fe._=Ut),this},Un.noop=cc,Un.now=Oa,Un.pad=function(t,e,n){t=gu(t);var r=(e=hu(e))?ln(t):0;if(!e||r>=e)return t;var o=(e-r)/2;return Vo(ye(o),n)+t+Vo(de(o),n)},Un.padEnd=function(t,e,n){t=gu(t);var r=(e=hu(e))?ln(t):0;return e&&re){var r=t;t=e,e=r}if(n||t%1||e%1){var i=wn();return gn(t+i*(e-t+ue("1e-"+((i+"").length-1))),e)}return Yr(t,e)},Un.reduce=function(t,e,n){var r=Ga(t)?Me:He,o=arguments.length<3;return r(t,ui(e,4),n,o,fr)},Un.reduceRight=function(t,e,n){var r=Ga(t)?je:He,o=arguments.length<3;return r(t,ui(e,4),n,o,pr)},Un.repeat=function(t,e,n){return e=(n?gi(t,e,n):e===o)?1:hu(e),Wr(gu(t),e)},Un.replace=function(){var t=arguments,e=gu(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Un.result=function(t,e,n){var r=-1,i=(e=go(e,t)).length;for(i||(i=1,t=o);++rf)return[];var n=d,r=gn(t,d);e=ui(e),t-=d;for(var o=We(r,e);++n=a)return t;var c=n-ln(r);if(c<1)return r;var s=u?_o(u,0,c).join(""):t.slice(0,c);if(i===o)return s+r;if(u&&(c+=s.length-c),iu(i)){if(t.slice(c).search(i)){var l,f=s;for(i.global||(i=Ot(i.source,gu(pt.exec(i))+"g")),i.lastIndex=0;l=i.exec(f);)var p=l.index;s=s.slice(0,p===o?c:p)}}else if(t.indexOf(uo(i),c)!=c){var d=s.lastIndexOf(i);d>-1&&(s=s.slice(0,d))}return s+r},Un.unescape=function(t){return(t=gu(t))&&W.test(t)?t.replace(H,dn):t},Un.uniqueId=function(t){var e=++Nt;return gu(t)+e},Un.upperCase=$u,Un.upperFirst=Qu,Un.each=ga,Un.eachRight=ba,Un.first=Yi,uc(Un,(mc={},br(Un,(function(t,e){jt.call(Un.prototype,e)||(mc[e]=t)})),mc),{chain:!1}),Un.VERSION="4.17.21",Ie(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Un[t].placeholder=Un})),Ie(["drop","take"],(function(t,e){Vn.prototype[t]=function(n){n=n===o?1:mn(hu(n),0);var r=this.__filtered__&&!e?new Vn(this):this.clone();return r.__filtered__?r.__takeCount__=gn(n,r.__takeCount__):r.__views__.push({size:gn(n,d),type:t+(r.__dir__<0?"Right":"")}),r},Vn.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}})),Ie(["filter","map","takeWhile"],(function(t,e){var n=e+1,r=1==n||3==n;Vn.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:ui(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}})),Ie(["head","last"],(function(t,e){var n="take"+(e?"Right":"");Vn.prototype[t]=function(){return this[n](1).value()[0]}})),Ie(["initial","tail"],(function(t,e){var n="drop"+(e?"":"Right");Vn.prototype[t]=function(){return this.__filtered__?new Vn(this):this[n](1)}})),Vn.prototype.compact=function(){return this.filter(rc)},Vn.prototype.find=function(t){return this.filter(t).head()},Vn.prototype.findLast=function(t){return this.reverse().find(t)},Vn.prototype.invokeMap=Kr((function(t,e){return"function"==typeof t?new Vn(this):this.map((function(n){return Ar(n,t,e)}))})),Vn.prototype.reject=function(t){return this.filter(Na(ui(t)))},Vn.prototype.slice=function(t,e){t=hu(t);var n=this;return n.__filtered__&&(t>0||e<0)?new Vn(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==o&&(n=(e=hu(e))<0?n.dropRight(-e):n.take(e-t)),n)},Vn.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Vn.prototype.toArray=function(){return this.take(d)},br(Vn.prototype,(function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),i=Un[r?"take"+("last"==e?"Right":""):e],a=r||/^find/.test(e);i&&(Un.prototype[e]=function(){var e=this.__wrapped__,u=r?[1]:arguments,c=e instanceof Vn,s=u[0],l=c||Ga(e),f=function(t){var e=i.apply(Un,Re([t],u));return r&&p?e[0]:e};l&&n&&"function"==typeof s&&1!=s.length&&(c=l=!1);var p=this.__chain__,d=!!this.__actions__.length,h=a&&!p,y=c&&!d;if(!a&&l){e=y?e:new Vn(this);var v=t.apply(e,u);return v.__actions__.push({func:da,args:[f],thisArg:o}),new qn(v,p)}return h&&y?t.apply(this,u):(v=this.thru(f),h?r?v.value()[0]:v.value():v)})})),Ie(["pop","push","shift","sort","splice","unshift"],(function(t){var e=At[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);Un.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var o=this.value();return e.apply(Ga(o)?o:[],t)}return this[n]((function(n){return e.apply(Ga(n)?n:[],t)}))}})),br(Vn.prototype,(function(t,e){var n=Un[e];if(n){var r=n.name+"";jt.call(xn,r)||(xn[r]=[]),xn[r].push({name:e,func:n})}})),xn[Uo(o,2).name]=[{name:"wrapper",func:o}],Vn.prototype.clone=function(){var t=new Vn(this.__wrapped__);return t.__actions__=To(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=To(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=To(this.__views__),t},Vn.prototype.reverse=function(){if(this.__filtered__){var t=new Vn(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},Vn.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=Ga(t),r=e<0,o=n?t.length:0,i=function(t,e,n){for(var r=-1,o=n.length;++r=this.__values__.length;return{done:t,value:t?o:this.__values__[this.__index__++]}},Un.prototype.plant=function(t){for(var e,n=this;n instanceof Bn;){var r=Ui(n);r.__index__=0,r.__values__=o,e?i.__wrapped__=r:e=r;var i=r;n=n.__wrapped__}return i.__wrapped__=t,e},Un.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Vn){var e=t;return this.__actions__.length&&(e=new Vn(this)),(e=e.reverse()).__actions__.push({func:da,args:[ta],thisArg:o}),new qn(e,this.__chain__)}return this.thru(ta)},Un.prototype.toJSON=Un.prototype.valueOf=Un.prototype.value=function(){return po(this.__wrapped__,this.__actions__)},Un.prototype.first=Un.prototype.head,Jt&&(Un.prototype[Jt]=function(){return this}),Un}();"function"==typeof define&&"object"==r(define.amd)&&define.amd?(fe._=hn,define((function(){return hn}))):de?((de.exports=hn)._=hn,pe._=hn):fe._=hn}.call(this)},95757:(t,e,n)=>{"use strict";n(91621),n(57188),n(80404),n(90291),n(32194),n(21894),n(11062);var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map((function(t){return e[t]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(t){r[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,a,u=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),c=1;c{"use strict";function r(t,e,n){return(e=function(t){var e=function(t){if("object"!==i(t)||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!==i(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===i(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,u=[],c=!0,s=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(u.push(r.value),u.length!==e);c=!0);}catch(t){s=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(s)throw o}}return u}}(t,e)||u(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function a(t){return function(t){if(Array.isArray(t))return c(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return c(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(t,e):void 0}}function c(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0})).join("&")},e.parseUrl=function(t,e){e=Object.assign({decode:!0},e);var n=o(f(t,"#"),2),r=n[0],i=n[1];return Object.assign({url:r.split("?")[0]||"",query:w(b(t),e)},e&&e.parseFragmentIdentifier&&i?{fragmentIdentifier:v(i,e)}:{})},e.stringifyUrl=function(t,n){n=Object.assign(r({encode:!0,strict:!0},d,!0),n);var o=g(t.url).split("?")[0]||"",i=e.extract(t.url),a=e.parse(i,{sort:!1}),u=Object.assign(a,t.query),c=e.stringify(u,n);c&&(c="?".concat(c));var s=function(t){var e="",n=t.indexOf("#");return-1!==n&&(e=t.slice(n)),e}(t.url);return t.fragmentIdentifier&&(s="#".concat(n[d]?y(t.fragmentIdentifier,n):t.fragmentIdentifier)),"".concat(o).concat(c).concat(s)},e.pick=function(t,n,o){o=Object.assign(r({parseFragmentIdentifier:!0},d,!1),o);var i=e.parseUrl(t,o),a=i.url,u=i.query,c=i.fragmentIdentifier;return e.stringifyUrl({url:a,query:p(u,n),fragmentIdentifier:c},o)},e.exclude=function(t,n,r){var o=Array.isArray(n)?function(t){return!n.includes(t)}:function(t,e){return!n(t,e)};return e.pick(t,o,r)}},73715:(t,e,n)=>{"use strict";n(13521),n(88315),n(53618),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%".concat(t.charCodeAt(0).toString(16).toUpperCase())}))}},87218:(t,e,n)=>{"use strict";n.r(e),n.d(e,{ArgumentOutOfRangeError:()=>x.k,AsyncSubject:()=>l.h,BehaviorSubject:()=>c.t,ConnectableObservable:()=>o.G,EMPTY:()=>$.w,EmptyError:()=>k.G,GroupedObservable:()=>i.k,NEVER:()=>lt,Notification:()=>I.E,NotificationKind:()=>I.I,ObjectUnsubscribedError:()=>R.P,Observable:()=>r.c,ReplaySubject:()=>s.m,Scheduler:()=>S._,Subject:()=>u.B7,Subscriber:()=>E.v,Subscription:()=>C.y,TimeoutError:()=>j.M,UnsubscriptionError:()=>M.Z,VirtualAction:()=>w,VirtualTimeScheduler:()=>_,animationFrame:()=>b,animationFrameScheduler:()=>g,asap:()=>f.I,asapScheduler:()=>f.$,async:()=>p.b,asyncScheduler:()=>p.E,bindCallback:()=>U,bindNodeCallback:()=>q,combineLatest:()=>Y.zV,concat:()=>W.x,config:()=>Tt.$,defer:()=>K.v,empty:()=>$.I,forkJoin:()=>J,from:()=>Z.H,fromEvent:()=>tt.R,fromEventPattern:()=>nt,generate:()=>rt,identity:()=>T.D,iif:()=>it,interval:()=>ut,isObservable:()=>A,merge:()=>st.h,never:()=>ft,noop:()=>P.l,observable:()=>a.s,of:()=>pt.of,onErrorResumeNext:()=>dt,pairs:()=>ht,partition:()=>bt,pipe:()=>O.F,queue:()=>d.g,queueScheduler:()=>d.T,race:()=>_t.O4,range:()=>wt,scheduled:()=>Pt.c,throwError:()=>Ct.$,timer:()=>Et.O,using:()=>It,zip:()=>Ot.yU});var r=n(97188),o=n(64952),i=n(40457),a=n(19241),u=n(47029),c=n(27399),s=n(39384),l=n(51073),f=n(35947),p=n(58687),d=n(22310),h=n(44693),y=n(12059),v=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return h.C6(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=requestAnimationFrame((function(){return e.flush(null)}))))},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(cancelAnimationFrame(n),e.scheduled=void 0)},e}(y.R),m=n(75998),g=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return h.C6(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,o=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++re.index?1:-1:t.delay>e.delay?1:-1},e}(y.R),S=n(90480),C=n(64264),E=n(72687),I=n(59038),O=n(7336),P=n(3784),T=n(63242);function A(t){return!!t&&(t instanceof r.c||"function"==typeof t.lift&&"function"==typeof t.subscribe)}var x=n(27943),k=n(88509),R=n(73404),M=n(55758),j=n(54467),N=(n(98556),n(20385)),D=n(96474),L=n(17815),z=n(11599);function U(t,e,n){if(e){if(!(0,z.m)(e))return function(){for(var r=[],o=0;o=e){r.complete();break}if(r.next(i++),r.closed)break}}))}function St(t){var e=t.start,n=t.index,r=t.count,o=t.subscriber;n>=r?o.complete():(o.next(e),o.closed||(t.index=n+1,t.start=e+1,this.schedule(t)))}var Ct=n(93033),Et=n(40930);function It(t,e){return new r.c((function(n){var r,o;try{r=t()}catch(t){return void n.error(t)}try{o=e(r)}catch(t){return void n.error(t)}var i=(o?(0,Z.H)(o):$.w).subscribe(n);return function(){i.unsubscribe(),r&&r.unsubscribe()}}))}var Ot=n(28124),Pt=n(64902),Tt=n(47255)},51073:(t,e,n)=>{"use strict";n.d(e,{h:()=>a});var r=n(44693),o=n(47029),i=n(64264),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.value=null,e.hasNext=!1,e.hasCompleted=!1,e}return r.C6(e,t),e.prototype._subscribe=function(e){return this.hasError?(e.error(this.thrownError),i.y.EMPTY):this.hasCompleted&&this.hasNext?(e.next(this.value),e.complete(),i.y.EMPTY):t.prototype._subscribe.call(this,e)},e.prototype.next=function(t){this.hasCompleted||(this.value=t,this.hasNext=!0)},e.prototype.error=function(e){this.hasCompleted||t.prototype.error.call(this,e)},e.prototype.complete=function(){this.hasCompleted=!0,this.hasNext&&t.prototype.next.call(this,this.value),t.prototype.complete.call(this)},e}(o.B7)},27399:(t,e,n)=>{"use strict";n.d(e,{t:()=>a});var r=n(44693),o=n(47029),i=n(73404),a=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return r.C6(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new i.P;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(o.B7)},59038:(t,e,n)=>{"use strict";n.d(e,{E:()=>u,I:()=>r});var r,o=n(79058),i=n(78274),a=n(93033);r||(r={});var u=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return(0,i.of)(this.value);case"E":return(0,a.$)(this.error);case"C":return(0,o.I)()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return void 0!==e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}()},97188:(t,e,n)=>{"use strict";n.d(e,{c:()=>c}),n(13521),n(67536),n(44594);var r=n(96474),o=n(10075),i=n(19241),a=n(7336),u=n(47255),c=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,i=(0,o.u)(t,e,n);if(r?i.add(r.call(i,this.source)):i.add(this.source||u.$.useDeprecatedSynchronousErrorHandling&&!i.syncErrorThrowable?this._subscribe(i):this._trySubscribe(i)),u.$.useDeprecatedSynchronousErrorHandling&&i.syncErrorThrowable&&(i.syncErrorThrowable=!1,i.syncErrorThrown))throw i.syncErrorValue;return i},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){u.$.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),(0,r.H)(t)?t.error(e):console.warn(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=s(e))((function(e,r){var o;o=n.subscribe((function(e){try{t(e)}catch(t){r(t),o&&o.unsubscribe()}}),r,e)}))},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[i.s]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e{"use strict";n.d(e,{I:()=>i});var r=n(47255),o=n(95292),i={closed:!0,next:function(t){},error:function(t){if(r.$.useDeprecatedSynchronousErrorHandling)throw t;(0,o.T)(t)},complete:function(){}}},82896:(t,e,n)=>{"use strict";n.d(e,{E:()=>o});var r=n(44693),o=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(n(72687).v)},39384:(t,e,n)=>{"use strict";n.d(e,{m:()=>l}),n(67068),n(25226);var r=n(44693),o=n(47029),i=n(22310),a=n(64264),u=n(67038),c=n(73404),s=n(43444),l=function(t){function e(e,n,r){void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY);var o=t.call(this)||this;return o.scheduler=r,o._events=[],o._infiniteTimeWindow=!1,o._bufferSize=e<1?1:e,o._windowTime=n<1?1:n,n===Number.POSITIVE_INFINITY?(o._infiniteTimeWindow=!0,o.next=o.nextInfiniteTimeWindow):o.next=o.nextTimeWindow,o}return r.C6(e,t),e.prototype.nextInfiniteTimeWindow=function(e){if(!this.isStopped){var n=this._events;n.push(e),n.length>this._bufferSize&&n.shift()}t.prototype.next.call(this,e)},e.prototype.nextTimeWindow=function(e){this.isStopped||(this._events.push(new f(this._getNow(),e)),this._trimBufferThenGetEvents()),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){var e,n=this._infiniteTimeWindow,r=n?this._events:this._trimBufferThenGetEvents(),o=this.scheduler,i=r.length;if(this.closed)throw new c.P;if(this.isStopped||this.hasError?e=a.y.EMPTY:(this.observers.push(t),e=new s.Y(this,t)),o&&t.add(t=new u.YZ(t,o)),n)for(var l=0;le&&(i=Math.max(i,o-e)),i>0&&r.splice(0,i),r},e}(o.B7),f=function(){return function(t,e){this.time=t,this.value=e}}()},90480:(t,e,n)=>{"use strict";n.d(e,{_:()=>r});var r=function(){function t(e,n){void 0===n&&(n=t.now),this.SchedulerAction=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.SchedulerAction(this,t).schedule(n,e)},t.now=function(){return Date.now()},t}()},47029:(t,e,n)=>{"use strict";n.d(e,{B7:()=>f,PJ:()=>l}),n(44396);var r=n(44693),o=n(97188),i=n(72687),a=n(64264),u=n(73404),c=n(43444),s=n(36956),l=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return r.C6(e,t),e}(i.v),f=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return r.C6(e,t),e.prototype[s.D]=function(){return new l(this)},e.prototype.lift=function(t){var e=new p(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new u.P;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),o=0;o{"use strict";n.d(e,{Y:()=>o}),n(47818),n(67068);var r=n(44693),o=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return r.C6(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(n(64264).y)},72687:(t,e,n)=>{"use strict";n.d(e,{v:()=>f}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var r=n(44693),o=n(95120),i=n(78191),a=n(64264),u=n(36956),c=n(47255),s=n(95292);function l(t){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l(t)}var f=function(t){function e(n,r,o){var a=t.call(this)||this;switch(a.syncErrorValue=null,a.syncErrorThrown=!1,a.syncErrorThrowable=!1,a.isStopped=!1,arguments.length){case 0:a.destination=i.I;break;case 1:if(!n){a.destination=i.I;break}if("object"===l(n)){n instanceof e?(a.syncErrorThrowable=n.syncErrorThrowable,a.destination=n,n.add(a)):(a.syncErrorThrowable=!0,a.destination=new p(a,n));break}default:a.syncErrorThrowable=!0,a.destination=new p(a,n,r,o)}return a}return r.C6(e,t),e.prototype[u.D]=function(){return this},e.create=function(t,n,r){var o=new e(t,n,r);return o.syncErrorThrowable=!1,o},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=t,this},e}(a.y),p=function(t){function e(e,n,r,a){var u,c=t.call(this)||this;c._parentSubscriber=e;var s=c;return(0,o.T)(n)?u=n:n&&(u=n.next,r=n.error,a=n.complete,n!==i.I&&(s=Object.create(n),(0,o.T)(s.unsubscribe)&&c.add(s.unsubscribe.bind(s)),s.unsubscribe=c.unsubscribe.bind(c))),c._context=s,c._next=u,c._error=r,c._complete=a,c}return r.C6(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;c.$.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=c.$.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):(0,s.T)(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;(0,s.T)(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};c.$.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){if(this.unsubscribe(),c.$.useDeprecatedSynchronousErrorHandling)throw t;(0,s.T)(t)}},e.prototype.__tryOrSetError=function(t,e,n){if(!c.$.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(e){return c.$.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=e,t.syncErrorThrown=!0,!0):((0,s.T)(e),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(f)},64264:(t,e,n)=>{"use strict";n.d(e,{y:()=>c}),n(91621),n(27481),n(90105),n(98556),n(47818),n(14718),n(67068),n(13521),n(25766),n(92947);var r=n(17815),o=n(46775),i=n(95120),a=n(55758);function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}var c=function(){function t(t){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,t&&(this._ctorUnsubscribe=!0,this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var e;if(!this.closed){var n=this,u=n._parentOrParents,c=n._ctorUnsubscribe,l=n._unsubscribe,f=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,u instanceof t)u.remove(this);else if(null!==u)for(var p=0;p{"use strict";n.d(e,{$:()=>o});var r=!1,o={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){t&&(new Error).stack,r=t},get useDeprecatedSynchronousErrorHandling(){return r}}},24813:(t,e,n)=>{"use strict";n.d(e,{gn:()=>c,tS:()=>s,zA:()=>u});var r=n(44693),o=n(72687),i=n(97188),a=n(57839),u=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,n}return r.C6(e,t),e.prototype._next=function(t){this.parent.notifyNext(t)},e.prototype._error=function(t){this.parent.notifyError(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},e}(o.v),c=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.notifyNext=function(t){this.destination.next(t)},e.prototype.notifyError=function(t){this.destination.error(t)},e.prototype.notifyComplete=function(){this.destination.complete()},e}(o.v);function s(t,e){if(!e.closed){if(t instanceof i.c)return t.subscribe(e);var n;try{n=(0,a.i)(t)(e)}catch(t){e.error(t)}return n}}},64952:(t,e,n)=>{"use strict";n.d(e,{G:()=>c,f:()=>s});var r=n(44693),o=n(47029),i=n(97188),a=n(64264),u=n(20643),c=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return r.C6(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new a.y).add(this.source.subscribe(new l(this.getSubject(),this))),t.closed&&(this._connection=null,t=a.y.EMPTY)),t},e.prototype.refCount=function(){return(0,u.B)()(this)},e}(i.c),s=function(){var t=c.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:t._subscribe},_isComplete:{value:t._isComplete,writable:!0},getSubject:{value:t.getSubject},connect:{value:t.connect},refCount:{value:t.refCount}}}(),l=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.C6(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(o.PJ)},60685:(t,e,n)=>{"use strict";n.d(e,{ZS:()=>f,zV:()=>l}),n(14718),n(44396),n(13521),n(92947);var r=n(44693),o=n(11599),i=n(17815),a=n(82896),u=n(2455),c=n(95270),s={};function l(){for(var t=[],e=0;e{"use strict";n.d(e,{x:()=>i});var r=n(78274),o=n(97824);function i(){for(var t=[],e=0;e{"use strict";n.d(e,{v:()=>a});var r=n(97188),o=n(37055),i=n(79058);function a(t){return new r.c((function(e){var n;try{n=t()}catch(t){return void e.error(t)}return(n?(0,o.H)(n):(0,i.I)()).subscribe(e)}))}},79058:(t,e,n)=>{"use strict";n.d(e,{I:()=>i,w:()=>o});var r=n(97188),o=new r.c((function(t){return t.complete()}));function i(t){return t?function(t){return new r.c((function(e){return t.schedule((function(){return e.complete()}))}))}(t):o}},37055:(t,e,n)=>{"use strict";n.d(e,{H:()=>a});var r=n(97188),o=n(57839),i=n(64902);function a(t,e){return e?(0,i.c)(t,e):t instanceof r.c?t:new r.c((0,o.i)(t))}},95270:(t,e,n)=>{"use strict";n.d(e,{c:()=>a});var r=n(97188),o=n(64118),i=n(84047);function a(t,e){return e?(0,i.V)(t,e):new r.c((0,o.v)(t))}},27671:(t,e,n)=>{"use strict";n.d(e,{R:()=>u}),n(44396),n(13521),n(88315);var r=n(97188),o=n(17815),i=n(95120),a=n(20385);function u(t,e,n,s){return(0,i.T)(n)&&(s=n,n=void 0),s?u(t,e,n).pipe((0,a.T)((function(t){return(0,o.c)(t)?s.apply(void 0,t):s(t)}))):new r.c((function(r){c(t,e,(function(t){arguments.length>1?r.next(Array.prototype.slice.call(arguments)):r.next(t)}),r,n)}))}function c(t,e,n,r,o){var i;if(function(t){return t&&"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener}(t)){var a=t;t.addEventListener(e,n,o),i=function(){return a.removeEventListener(e,n,o)}}else if(function(t){return t&&"function"==typeof t.on&&"function"==typeof t.off}(t)){var u=t;t.on(e,n),i=function(){return u.off(e,n)}}else if(function(t){return t&&"function"==typeof t.addListener&&"function"==typeof t.removeListener}(t)){var s=t;t.addListener(e,n),i=function(){return s.removeListener(e,n)}}else{if(!t||!t.length)throw new TypeError("Invalid event target");for(var l=0,f=t.length;l{"use strict";n.d(e,{h:()=>u}),n(25226);var r=n(97188),o=n(11599),i=n(38948),a=n(95270);function u(){for(var t=[],e=0;e1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof c&&(n=t.pop()),null===u&&1===t.length&&t[0]instanceof r.c?t[0]:(0,i.U)(n)((0,a.c)(t,u))}},78274:(t,e,n)=>{"use strict";n.d(e,{of:()=>a});var r=n(11599),o=n(95270),i=n(84047);function a(){for(var t=[],e=0;e{"use strict";n.d(e,{O4:()=>c});var r=n(44693),o=n(17815),i=n(95270),a=n(82896),u=n(2455);function c(){for(var t=[],e=0;e{"use strict";n.d(e,{$:()=>o});var r=n(97188);function o(t,e){return e?new r.c((function(n){return e.schedule(i,0,{error:t,subscriber:n})})):new r.c((function(e){return e.error(t)}))}function i(t){var e=t.error;t.subscriber.error(e)}},40930:(t,e,n)=>{"use strict";n.d(e,{O:()=>u}),n(25226);var r=n(97188),o=n(58687),i=n(16745),a=n(11599);function u(t,e,n){void 0===t&&(t=0);var u=-1;return(0,i.k)(e)?u=Number(e)<1?1:Number(e):(0,a.m)(e)&&(n=e),(0,a.m)(n)||(n=o.b),new r.c((function(e){var r=(0,i.k)(t)?t:+t-n.now();return n.schedule(c,r,{index:0,period:u,subscriber:e})}))}function c(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}}},28124:(t,e,n)=>{"use strict";n.d(e,{ee:()=>l,yU:()=>s});var r=n(44693),o=n(95270),i=n(17815),a=n(72687),u=n(8034),c=n(24813);function s(){for(var t=[],e=0;ethis.index},t.prototype.hasCompleted=function(){return this.array.length===this.index},t}(),h=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.parent=n,o.observable=r,o.stillUnsubscribed=!0,o.buffer=[],o.isComplete=!1,o}return r.C6(e,t),e.prototype[u.lJ]=function(){return this},e.prototype.next=function(){var t=this.buffer;return 0===t.length&&this.isComplete?{value:null,done:!0}:{value:t.shift(),done:!1}},e.prototype.hasValue=function(){return this.buffer.length>0},e.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},e.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},e.prototype.notifyNext=function(t){this.buffer.push(t),this.parent.checkIterators()},e.prototype.subscribe=function(){return(0,c.tS)(this.observable,new c.zA(this))},e}(c.gn)},26540:(t,e,n)=>{"use strict";n.d(e,{W:()=>i});var r=n(44693),o=n(24813);function i(t){return function(e){var n=new a(t),r=e.lift(n);return n.caught=r}}var a=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.selector,this.caught))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.selector=n,o.caught=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(e){return void t.prototype.error.call(this,e)}this._unsubscribeAndRecycle();var r=new o.zA(this);this.add(r);var i=(0,o.tS)(n,r);i!==r&&this.add(i)}},e}(o.gn)},97824:(t,e,n)=>{"use strict";n.d(e,{K:()=>o});var r=n(38948);function o(){return(0,r.U)(1)}},59788:(t,e,n)=>{"use strict";n.d(e,{c:()=>c});var r=n(44693),o=n(58687),i=n(54948),a=n(72687),u=n(59038);function c(t,e){void 0===e&&(e=o.b);var n=(0,i.$)(t)?+t-e.now():Math.abs(t);return function(t){return t.lift(new s(n,e))}}var s=function(){function t(t,e){this.delay=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new l(t,this.delay,this.scheduler))},t}(),l=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return r.C6(e,t),e.dispatch=function(t){for(var e=t.source,n=e.queue,r=t.scheduler,o=t.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(t,i)}else this.unsubscribe(),e.active=!1},e.prototype._schedule=function(t){this.active=!0,this.destination.add(t.schedule(e.dispatch,this.delay,{source:this,destination:this.destination,scheduler:t}))},e.prototype.scheduleNotification=function(t){if(!0!==this.errored){var e=this.scheduler,n=new f(e.now()+this.delay,t);this.queue.push(n),!1===this.active&&this._schedule(e)}},e.prototype._next=function(t){this.scheduleNotification(u.E.createNext(t))},e.prototype._error=function(t){this.errored=!0,this.queue=[],this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.scheduleNotification(u.E.createComplete()),this.unsubscribe()},e}(a.v),f=function(){return function(t,e){this.time=t,this.notification=e}}()},17507:(t,e,n)=>{"use strict";n.d(e,{F:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.compare=t,this.keySelector=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.compare,this.keySelector))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return r.C6(e,t),e.prototype.compare=function(t,e){return t===e},e.prototype._next=function(t){var e;try{var n=this.keySelector;e=n?n(t):t}catch(t){return this.destination.error(t)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,e)}catch(t){return this.destination.error(t)}else this.hasKey=!0;r||(this.key=e,this.destination.next(t))},e}(o.v)},6245:(t,e,n)=>{"use strict";n.d(e,{p:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.predicate,this.thisArg))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}e&&this.destination.next(t)},e}(o.v)},40457:(t,e,n)=>{"use strict";n.d(e,{$:()=>c,k:()=>p}),n(14718),n(20363),n(13521),n(25766),n(44594),n(92947);var r=n(44693),o=n(72687),i=n(64264),a=n(97188),u=n(47029);function c(t,e,n,r){return function(o){return o.lift(new s(t,e,n,r))}}var s=function(){function t(t,e,n,r){this.keySelector=t,this.elementSelector=e,this.durationSelector=n,this.subjectSelector=r}return t.prototype.call=function(t,e){return e.subscribe(new l(t,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))},t}(),l=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;return a.keySelector=n,a.elementSelector=r,a.durationSelector=o,a.subjectSelector=i,a.groups=null,a.attemptedToUnsubscribe=!1,a.count=0,a}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.keySelector(t)}catch(t){return void this.error(t)}this._group(t,e)},e.prototype._group=function(t,e){var n=this.groups;n||(n=this.groups=new Map);var r,o=n.get(e);if(this.elementSelector)try{r=this.elementSelector(t)}catch(t){this.error(t)}else r=t;if(!o){o=this.subjectSelector?this.subjectSelector():new u.B7,n.set(e,o);var i=new p(e,o,this);if(this.destination.next(i),this.durationSelector){var a=void 0;try{a=this.durationSelector(new p(e,o))}catch(t){return void this.error(t)}this.add(a.subscribe(new f(e,o,this)))}}o.closed||o.next(r)},e.prototype._error=function(t){var e=this.groups;e&&(e.forEach((function(e,n){e.error(t)})),e.clear()),this.destination.error(t)},e.prototype._complete=function(){var t=this.groups;t&&(t.forEach((function(t,e){t.complete()})),t.clear()),this.destination.complete()},e.prototype.removeGroup=function(t){this.groups.delete(t)},e.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=!0,0===this.count&&t.prototype.unsubscribe.call(this))},e}(o.v),f=function(t){function e(e,n,r){var o=t.call(this,n)||this;return o.key=e,o.group=n,o.parent=r,o}return r.C6(e,t),e.prototype._next=function(t){this.complete()},e.prototype._unsubscribe=function(){var t=this.parent,e=this.key;this.key=this.parent=null,t&&t.removeGroup(e)},e}(o.v),p=function(t){function e(e,n,r){var o=t.call(this)||this;return o.key=e,o.groupSubject=n,o.refCountSubscription=r,o}return r.C6(e,t),e.prototype._subscribe=function(t){var e=new i.y,n=this.refCountSubscription,r=this.groupSubject;return n&&!n.closed&&e.add(new d(n)),e.add(r.subscribe(t)),e},e}(a.c),d=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,e.count++,n}return r.C6(e,t),e.prototype.unsubscribe=function(){var e=this.parent;e.closed||this.closed||(t.prototype.unsubscribe.call(this),e.count-=1,0===e.count&&e.attemptedToUnsubscribe&&e.unsubscribe())},e}(i.y)},20385:(t,e,n)=>{"use strict";n.d(e,{T:()=>i});var r=n(44693),o=n(72687);function i(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.project,this.thisArg))},t}(),u=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return r.C6(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(o.v)},38948:(t,e,n)=>{"use strict";n.d(e,{U:()=>i}),n(25226);var r=n(75453),o=n(63242);function i(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),(0,r.ZZ)(o.D,t)}},75453:(t,e,n)=>{"use strict";n.d(e,{ZZ:()=>u,qI:()=>l}),n(25226);var r=n(44693),o=n(20385),i=n(37055),a=n(24813);function u(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(u((function(n,r){return(0,i.H)(t(n,r)).pipe((0,o.T)((function(t,o){return e(n,t,r,o)})))}),n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new c(t,n))})}var c=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.project,this.concurrent))},t}(),s=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=t.call(this,e)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return r.C6(e,t),e.prototype._next=function(t){this.active0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(a.gn),l=u},67038:(t,e,n)=>{"use strict";n.d(e,{QE:()=>a,YZ:()=>c});var r=n(44693),o=n(72687),i=n(59038);function a(t,e){return void 0===e&&(e=0),function(n){return n.lift(new u(t,e))}}var u=function(){function t(t,e){void 0===e&&(e=0),this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.scheduler,this.delay))},t}(),c=function(t){function e(e,n,r){void 0===r&&(r=0);var o=t.call(this,e)||this;return o.scheduler=n,o.delay=r,o}return r.C6(e,t),e.dispatch=function(t){var e=t.notification,n=t.destination;e.observe(n),this.unsubscribe()},e.prototype.scheduleMessage=function(t){this.destination.add(this.scheduler.schedule(e.dispatch,this.delay,new s(t,this.destination)))},e.prototype._next=function(t){this.scheduleMessage(i.E.createNext(t))},e.prototype._error=function(t){this.scheduleMessage(i.E.createError(t)),this.unsubscribe()},e.prototype._complete=function(){this.scheduleMessage(i.E.createComplete()),this.unsubscribe()},e}(o.v),s=function(){return function(t,e){this.notification=t,this.destination=e}}()},20643:(t,e,n)=>{"use strict";n.d(e,{B:()=>i});var r=n(44693),o=n(72687);function i(){return function(t){return t.lift(new a(t))}}var a=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new u(t,n),o=e.subscribe(r);return r.closed||(r.connection=n.connect()),o},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.C6(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(o.v)},37405:(t,e,n)=>{"use strict";n.d(e,{l:()=>a});var r=n(44693),o=n(47029),i=n(24813);function a(t){return function(e){return e.lift(new u(t,e))}}var u=function(){function t(t,e){this.notifier=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.notifier,this.source))},t}(),c=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.notifier=n,o.source=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.errors,r=this.retries,a=this.retriesSubscription;if(r)this.errors=void 0,this.retriesSubscription=void 0;else{n=new o.B7;try{r=(0,this.notifier)(n)}catch(e){return t.prototype.error.call(this,e)}a=(0,i.tS)(r,new i.zA(this))}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=a,n.next(e)}},e.prototype._unsubscribe=function(){var t=this.errors,e=this.retriesSubscription;t&&(t.unsubscribe(),this.errors=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype.notifyNext=function(){var t=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=t,this.source.subscribe(this)},e}(i.gn)},9099:(t,e,n)=>{"use strict";n.d(e,{t:()=>i}),n(91621),n(27481),n(90105),n(14718),n(25226),n(13521),n(25766),n(92947);var r=n(39384);function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function i(t,e,n){var i;return i=t&&"object"===o(t)?t:{bufferSize:t,windowTime:e,refCount:!1,scheduler:n},function(t){return t.lift(function(t){var e,n,o=t.bufferSize,i=void 0===o?Number.POSITIVE_INFINITY:o,a=t.windowTime,u=void 0===a?Number.POSITIVE_INFINITY:a,c=t.refCount,s=t.scheduler,l=0,f=!1,p=!1;return function(t){var o;l++,!e||f?(f=!1,e=new r.m(i,u,s),o=e.subscribe(this),n=t.subscribe({next:function(t){e.next(t)},error:function(t){f=!0,e.error(t)},complete:function(){p=!0,n=void 0,e.complete()}}),p&&(n=void 0)):o=e.subscribe(this),this.add((function(){l--,o.unsubscribe(),o=void 0,n&&!p&&c&&0===l&&(n.unsubscribe(),n=void 0,e=void 0)}))}}(i))}}},45893:(t,e,n)=>{"use strict";n.d(e,{n:()=>u});var r=n(44693),o=n(20385),i=n(37055),a=n(24813);function u(t,e){return"function"==typeof e?function(n){return n.pipe(u((function(n,r){return(0,i.H)(t(n,r)).pipe((0,o.T)((function(t,o){return e(n,t,r,o)})))})))}:function(e){return e.lift(new c(t))}}var c=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.project))},t}(),s=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return r.C6(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this._innerSub(e)},e.prototype._innerSub=function(t){var e=this.innerSubscription;e&&e.unsubscribe();var n=new a.zA(this),r=this.destination;r.add(n),this.innerSubscription=(0,a.tS)(t,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=void 0},e.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t){this.destination.next(t)},e}(a.gn)},78920:(t,e,n)=>{"use strict";n.d(e,{s:()=>u});var r=n(44693),o=n(72687),i=n(27943),a=n(79058);function u(t){return function(e){return 0===t?(0,a.I)():e.lift(new c(t))}}var c=function(){function t(t){if(this.total=t,this.total<0)throw new i.k}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.total))},t}(),s=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(o.v)},84047:(t,e,n)=>{"use strict";n.d(e,{V:()=>i});var r=n(97188),o=n(64264);function i(t,e){return new r.c((function(n){var r=new o.y,i=0;return r.add(e.schedule((function(){i!==t.length?(n.next(t[i++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}},37458:(t,e,n)=>{"use strict";n.d(e,{S:()=>a});var r=n(97188),o=n(64264),i=n(8034);function a(t,e){if(!t)throw new Error("Iterable cannot be null");return new r.c((function(n){var r,a=new o.y;return a.add((function(){r&&"function"==typeof r.return&&r.return()})),a.add(e.schedule((function(){r=t[i.lJ](),a.add(e.schedule((function(){if(!n.closed){var t,e;try{var o=r.next();t=o.value,e=o.done}catch(t){return void n.error(t)}e?n.complete():(n.next(t),this.schedule())}})))}))),a}))}},15737:(t,e,n)=>{"use strict";n.d(e,{x:()=>a});var r=n(97188),o=n(64264),i=n(19241);function a(t,e){return new r.c((function(n){var r=new o.y;return r.add(e.schedule((function(){var o=t[i.s]();r.add(o.subscribe({next:function(t){r.add(e.schedule((function(){return n.next(t)})))},error:function(t){r.add(e.schedule((function(){return n.error(t)})))},complete:function(){r.add(e.schedule((function(){return n.complete()})))}}))}))),r}))}},94479:(t,e,n)=>{"use strict";n.d(e,{P:()=>i});var r=n(97188),o=n(64264);function i(t,e){return new r.c((function(n){var r=new o.y;return r.add(e.schedule((function(){return t.then((function(t){r.add(e.schedule((function(){n.next(t),r.add(e.schedule((function(){return n.complete()})))})))}),(function(t){r.add(e.schedule((function(){return n.error(t)})))}))}))),r}))}},64902:(t,e,n)=>{"use strict";n.d(e,{c:()=>p}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var r=n(15737),o=n(94479),i=n(84047),a=n(37458),u=n(71206),c=n(40535),s=n(42736),l=n(46234);function f(t){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},f(t)}function p(t,e){if(null!=t){if((0,u.l)(t))return(0,r.x)(t,e);if((0,c.y)(t))return(0,o.P)(t,e);if((0,s.X)(t))return(0,i.V)(t,e);if((0,l.x)(t)||"string"==typeof t)return(0,a.S)(t,e)}throw new TypeError((null!==t&&f(t)||t)+" is not observable")}},12059:(t,e,n)=>{"use strict";n.d(e,{R:()=>o}),n(47818),n(67068);var r=n(44693),o=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return r.C6(e,t),e.prototype.schedule=function(t,e){if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this},e.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),setInterval(t.flush.bind(t,this),n)},e.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return e;clearInterval(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var n=!1,r=void 0;try{this.work(t)}catch(t){n=!0,r=!!t&&t||new Error(t)}if(n)return this.unsubscribe(),r},e.prototype._unsubscribe=function(){var t=this.id,e=this.scheduler,n=e.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null},e}(function(t){function e(e,n){return t.call(this)||this}return r.C6(e,t),e.prototype.schedule=function(t,e){return void 0===e&&(e=0),this},e}(n(64264).y))},75998:(t,e,n)=>{"use strict";n.d(e,{q:()=>i});var r=n(44693),o=n(90480),i=function(t){function e(n,r){void 0===r&&(r=o._.now);var i=t.call(this,n,(function(){return e.delegate&&e.delegate!==i?e.delegate.now():r()}))||this;return i.actions=[],i.active=!1,i.scheduled=void 0,i}return r.C6(e,t),e.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),e.delegate&&e.delegate!==this?e.delegate.schedule(n,r,o):t.prototype.schedule.call(this,n,r,o)},e.prototype.flush=function(t){var e=this.actions;if(this.active)e.push(t);else{var n;this.active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this.active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},e}(o._)},35947:(t,e,n)=>{"use strict";n.d(e,{I:()=>l,$:()=>s});var r=n(44693),o=(n(21894),n(13521),n(67536),1),i=function(){return Promise.resolve()}(),a={};function u(t){return t in a&&(delete a[t],!0)}var c=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.C6(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=(c=e.flush.bind(e,null),s=o++,a[s]=!0,i.then((function(){return u(s)&&c()})),s)));var c,s},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(u(n),e.scheduled=void 0)},e}(n(12059).R),s=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,o=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++r{"use strict";n.d(e,{E:()=>o,b:()=>i});var r=n(12059),o=new(n(75998).q)(r.R),i=o},22310:(t,e,n)=>{"use strict";n.d(e,{g:()=>a,T:()=>i});var r=n(44693),o=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.C6(e,t),e.prototype.schedule=function(e,n){return void 0===n&&(n=0),n>0?t.prototype.schedule.call(this,e,n):(this.delay=n,this.state=e,this.scheduler.flush(this),this)},e.prototype.execute=function(e,n){return n>0||this.closed?t.prototype.execute.call(this,e,n):this._execute(e,n)},e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?t.prototype.requestAsyncId.call(this,e,n,r):e.flush(this)},e}(n(12059).R),i=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e}(n(75998).q))(o),a=i},8034:(t,e,n)=>{"use strict";function r(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}n.d(e,{lJ:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947);var o=r()},19241:(t,e,n)=>{"use strict";n.d(e,{s:()=>r}),n(91621),n(27481),n(13521);var r=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}()},36956:(t,e,n)=>{"use strict";n.d(e,{D:()=>r}),n(91621),n(27481),n(13521);var r=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}()},27943:(t,e,n)=>{"use strict";n.d(e,{k:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return t.prototype=Object.create(Error.prototype),t}()},88509:(t,e,n)=>{"use strict";n.d(e,{G:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}return t.prototype=Object.create(Error.prototype),t}()},73404:(t,e,n)=>{"use strict";n.d(e,{P:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return t.prototype=Object.create(Error.prototype),t}()},54467:(t,e,n)=>{"use strict";n.d(e,{M:()=>r}),n(18864);var r=function(){function t(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return t.prototype=Object.create(Error.prototype),t}()},55758:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r}),n(57188),n(80404),n(18864),n(13521),n(88315);var r=function(){function t(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}return t.prototype=Object.create(Error.prototype),t}()},96474:(t,e,n)=>{"use strict";n.d(e,{H:()=>o});var r=n(72687);function o(t){for(;t;){var e=t,n=e.closed,o=e.destination,i=e.isStopped;if(n||i)return!1;t=o&&o instanceof r.v?o:null}return!0}},95292:(t,e,n)=>{"use strict";function r(t){setTimeout((function(){throw t}),0)}n.d(e,{T:()=>r})},63242:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{D:()=>r})},17815:(t,e,n)=>{"use strict";n.d(e,{c:()=>r});var r=function(){return Array.isArray||function(t){return t&&"number"==typeof t.length}}()},42736:(t,e,n)=>{"use strict";n.d(e,{X:()=>r});var r=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t}},54948:(t,e,n)=>{"use strict";function r(t){return t instanceof Date&&!isNaN(+t)}n.d(e,{$:()=>r})},95120:(t,e,n)=>{"use strict";function r(t){return"function"==typeof t}n.d(e,{T:()=>r})},71206:(t,e,n)=>{"use strict";n.d(e,{l:()=>o});var r=n(19241);function o(t){return t&&"function"==typeof t[r.s]}},46234:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(8034);function o(t){return t&&"function"==typeof t[r.lJ]}},16745:(t,e,n)=>{"use strict";n.d(e,{k:()=>o}),n(8933);var r=n(17815);function o(t){return!(0,r.c)(t)&&t-parseFloat(t)+1>=0}},46775:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return null!==t&&"object"===r(t)}n.d(e,{G:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947)},40535:(t,e,n)=>{"use strict";function r(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}n.d(e,{y:()=>r})},11599:(t,e,n)=>{"use strict";function r(t){return t&&"function"==typeof t.schedule}n.d(e,{m:()=>r})},3784:(t,e,n)=>{"use strict";function r(){}n.d(e,{l:()=>r})},80503:(t,e,n)=>{"use strict";function r(t,e){function n(){return!n.pred.apply(n.thisArg,arguments)}return n.pred=t,n.thisArg=e,n}n.d(e,{A:()=>r})},7336:(t,e,n)=>{"use strict";n.d(e,{F:()=>o,m:()=>i});var r=n(63242);function o(){for(var t=[],e=0;e{"use strict";n.d(e,{i:()=>p});var r=n(64118),o=n(42066),i=n(6261),a=n(49954),u=n(42736),c=n(40535),s=n(46775),l=n(8034),f=n(19241),p=function(t){if(t&&"function"==typeof t[f.s])return(0,a.X)(t);if((0,u.X)(t))return(0,r.v)(t);if((0,c.y)(t))return(0,o.F)(t);if(t&&"function"==typeof t[l.lJ])return(0,i.S)(t);var e=(0,s.G)(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+e+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")}},64118:(t,e,n)=>{"use strict";n.d(e,{v:()=>r});var r=function(t){return function(e){for(var n=0,r=t.length;n{"use strict";n.d(e,{S:()=>o});var r=n(8034),o=function(t){return function(e){for(var n=t[r.lJ]();;){var o=void 0;try{o=n.next()}catch(t){return e.error(t),e}if(o.done){e.complete();break}if(e.next(o.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e}}},49954:(t,e,n)=>{"use strict";n.d(e,{X:()=>o});var r=n(19241),o=function(t){return function(e){var n=t[r.s]();if("function"!=typeof n.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return n.subscribe(e)}}},42066:(t,e,n)=>{"use strict";n.d(e,{F:()=>o});var r=n(95292),o=function(t){return function(e){return t.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,r.T),e}}},2455:(t,e,n)=>{"use strict";n.d(e,{F:()=>u});var r=n(44693),o=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parent=e,o.outerValue=n,o.outerIndex=r,o.index=0,o}return r.C6(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n(72687).v),i=n(57839),a=n(97188);function u(t,e,n,r,u){if(void 0===u&&(u=new o(t,n,r)),!u.closed)return e instanceof a.c?e.subscribe(u):(0,i.i)(e)(u)}},10075:(t,e,n)=>{"use strict";n.d(e,{u:()=>a});var r=n(72687),o=n(36956),i=n(78191);function a(t,e,n){if(t){if(t instanceof r.v)return t;if(t[o.D])return t[o.D]()}return t||e||n?new r.v(t,e,n):new r.v(i.I)}},57532:(t,e,n)=>{"use strict";n.r(e),n.d(e,{audit:()=>i,auditTime:()=>l,buffer:()=>f,bufferCount:()=>y,bufferTime:()=>_,bufferToggle:()=>x,bufferWhen:()=>M,catchError:()=>D.W,combineAll:()=>z,combineLatest:()=>B,concat:()=>V,concatAll:()=>G.K,concatMap:()=>Y,concatMapTo:()=>W,count:()=>K,debounce:()=>Z,debounceTime:()=>tt,defaultIfEmpty:()=>ot,delay:()=>ut.c,delayWhen:()=>st,dematerialize:()=>ht,distinct:()=>mt,distinctUntilChanged:()=>_t.F,distinctUntilKeyChanged:()=>wt,elementAt:()=>xt,endWith:()=>Rt,every:()=>Mt,exhaust:()=>Dt,exhaustMap:()=>Ft,expand:()=>Vt,filter:()=>Ct.p,finalize:()=>Yt,find:()=>$t,findIndex:()=>Jt,first:()=>te,flatMap:()=>H.qI,groupBy:()=>ee.$,ignoreElements:()=>ne,isEmpty:()=>ie,last:()=>pe,map:()=>Ut.T,mapTo:()=>de,materialize:()=>me,max:()=>Ie,merge:()=>Pe,mergeAll:()=>Te.U,mergeMap:()=>H.ZZ,mergeMapTo:()=>Ae,mergeScan:()=>xe,min:()=>Me,multicast:()=>Ne,observeOn:()=>Le.QE,onErrorResumeNext:()=>ze,pairwise:()=>Be,partition:()=>He,pluck:()=>Ye,publish:()=>Ke,publishBehavior:()=>Qe,publishLast:()=>Je,publishReplay:()=>tn,race:()=>nn,reduce:()=>Ee,refCount:()=>hn.B,repeat:()=>rn,repeatWhen:()=>un,retry:()=>ln,retryWhen:()=>dn.l,sample:()=>yn,sampleTime:()=>gn,scan:()=>_e,sequenceEqual:()=>Sn,share:()=>Pn,shareReplay:()=>Tn.t,single:()=>An,skip:()=>Rn,skipLast:()=>Nn,skipUntil:()=>zn,skipWhile:()=>Bn,startWith:()=>Gn,subscribeOn:()=>Kn,switchAll:()=>Zn,switchMap:()=>Qn.n,switchMapTo:()=>Jn,take:()=>At.s,takeLast:()=>se,takeUntil:()=>Xn,takeWhile:()=>nr,tap:()=>ur,throttle:()=>fr,throttleTime:()=>hr,throwIfEmpty:()=>It,timeInterval:()=>br,timeout:()=>Pr,timeoutWith:()=>Cr,timestamp:()=>Tr,toArray:()=>kr,window:()=>Rr,windowCount:()=>Nr,windowTime:()=>zr,windowToggle:()=>Hr,windowWhen:()=>Kr,withLatestFrom:()=>Zr,zip:()=>eo,zipAll:()=>no});var r=n(44693),o=n(24813);function i(t){return function(e){return e.lift(new a(t))}}var a=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.durationSelector))},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r}return r.C6(e,t),e.prototype._next=function(t){if(this.value=t,this.hasValue=!0,!this.throttled){var e=void 0;try{e=(0,this.durationSelector)(t)}catch(t){return this.destination.error(t)}var n=(0,o.tS)(e,new o.zA(this));!n||n.closed?this.clearThrottle():this.add(this.throttled=n)}},e.prototype.clearThrottle=function(){var t=this,e=t.value,n=t.hasValue,r=t.throttled;r&&(this.remove(r),this.throttled=void 0,r.unsubscribe()),n&&(this.value=void 0,this.hasValue=!1,this.destination.next(e))},e.prototype.notifyNext=function(){this.clearThrottle()},e.prototype.notifyComplete=function(){this.clearThrottle()},e}(o.gn),c=n(58687),s=n(40930);function l(t,e){return void 0===e&&(e=c.b),i((function(){return(0,s.O)(t,e)}))}function f(t){return function(e){return e.lift(new p(t))}}var p=function(){function t(t){this.closingNotifier=t}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.closingNotifier))},t}(),d=function(t){function e(e,n){var r=t.call(this,e)||this;return r.buffer=[],r.add((0,o.tS)(n,new o.zA(r))),r}return r.C6(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype.notifyNext=function(){var t=this.buffer;this.buffer=[],this.destination.next(t)},e}(o.gn),h=(n(67068),n(72687));function y(t,e){return void 0===e&&(e=null),function(n){return n.lift(new v(t,e))}}var v=function(){function t(t,e){this.bufferSize=t,this.startBufferEvery=e,this.subscriberClass=e&&t!==e?g:m}return t.prototype.call=function(t,e){return e.subscribe(new this.subscriberClass(t,this.bufferSize,this.startBufferEvery))},t}(),m=function(t){function e(e,n){var r=t.call(this,e)||this;return r.bufferSize=n,r.buffer=[],r}return r.C6(e,t),e.prototype._next=function(t){var e=this.buffer;e.push(t),e.length==this.bufferSize&&(this.destination.next(e),this.buffer=[])},e.prototype._complete=function(){var e=this.buffer;e.length>0&&this.destination.next(e),t.prototype._complete.call(this)},e}(h.v),g=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.bufferSize=n,o.startBufferEvery=r,o.buffers=[],o.count=0,o}return r.C6(e,t),e.prototype._next=function(t){var e=this,n=e.bufferSize,r=e.startBufferEvery,o=e.buffers,i=e.count;this.count++,i%r==0&&o.push([]);for(var a=o.length;a--;){var u=o[a];u.push(t),u.length===n&&(o.splice(a,1),this.destination.next(u))}},e.prototype._complete=function(){for(var e=this.buffers,n=this.destination;e.length>0;){var r=e.shift();r.length>0&&n.next(r)}t.prototype._complete.call(this)},e}(h.v),b=(n(47818),n(25226),n(11599));function _(t){var e=arguments.length,n=c.b;(0,b.m)(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],e--);var r=null;e>=2&&(r=arguments[1]);var o=Number.POSITIVE_INFINITY;return e>=3&&(o=arguments[2]),function(e){return e.lift(new w(t,r,o,n))}}var w=function(){function t(t,e,n,r){this.bufferTimeSpan=t,this.bufferCreationInterval=e,this.maxBufferSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new C(t,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},t}(),S=function(){return function(){this.buffer=[]}}(),C=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;a.bufferTimeSpan=n,a.bufferCreationInterval=r,a.maxBufferSize=o,a.scheduler=i,a.contexts=[];var u=a.openContext();if(a.timespanOnly=null==r||r<0,a.timespanOnly){var c={subscriber:a,context:u,bufferTimeSpan:n};a.add(u.closeAction=i.schedule(E,n,c))}else{var s={subscriber:a,context:u},l={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:a,scheduler:i};a.add(u.closeAction=i.schedule(O,n,s)),a.add(i.schedule(I,r,l))}return a}return r.C6(e,t),e.prototype._next=function(t){for(var e,n=this.contexts,r=n.length,o=0;o0;){var r=e.shift();n.next(r.buffer)}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.contexts=null},e.prototype.onBufferFull=function(t){this.closeContext(t);var e=t.closeAction;if(e.unsubscribe(),this.remove(e),!this.closed&&this.timespanOnly){t=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:t,bufferTimeSpan:n};this.add(t.closeAction=this.scheduler.schedule(E,n,r))}},e.prototype.openContext=function(){var t=new S;return this.contexts.push(t),t},e.prototype.closeContext=function(t){this.destination.next(t.buffer);var e=this.contexts;(e?e.indexOf(t):-1)>=0&&e.splice(e.indexOf(t),1)},e}(h.v);function E(t){var e=t.subscriber,n=t.context;n&&e.closeContext(n),e.closed||(t.context=e.openContext(),t.context.closeAction=this.schedule(t,t.bufferTimeSpan))}function I(t){var e=t.bufferCreationInterval,n=t.bufferTimeSpan,r=t.subscriber,o=t.scheduler,i=r.openContext();r.closed||(r.add(i.closeAction=o.schedule(O,n,{subscriber:r,context:i})),this.schedule(t,e))}function O(t){var e=t.subscriber,n=t.context;e.closeContext(n)}var P=n(64264),T=n(2455),A=n(82896);function x(t,e){return function(n){return n.lift(new k(t,e))}}var k=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new R(t,this.openings,this.closingSelector))},t}(),R=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.closingSelector=r,o.contexts=[],o.add((0,T.F)(o,n)),o}return r.C6(e,t),e.prototype._next=function(t){for(var e=this.contexts,n=e.length,r=0;r0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts;e.length>0;){var n=e.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e){t?this.closeBuffer(t):this.openBuffer(e)},e.prototype.notifyComplete=function(t){this.closeBuffer(t.context)},e.prototype.openBuffer=function(t){try{var e=this.closingSelector.call(this,t);e&&this.trySubscribe(e)}catch(t){this._error(t)}},e.prototype.closeBuffer=function(t){var e=this.contexts;if(e&&t){var n=t.buffer,r=t.subscription;this.destination.next(n),e.splice(e.indexOf(t),1),this.remove(r),r.unsubscribe()}},e.prototype.trySubscribe=function(t){var e=this.contexts,n=new P.y,r={buffer:[],subscription:n};e.push(r);var o=(0,T.F)(this,t,r);!o||o.closed?this.closeBuffer(r):(o.context=r,this.add(o),n.add(o))},e}(A.E);function M(t){return function(e){return e.lift(new j(t))}}var j=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new N(t,this.closingSelector))},t}(),N=function(t){function e(e,n){var r=t.call(this,e)||this;return r.closingSelector=n,r.subscribing=!1,r.openBuffer(),r}return r.C6(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype._complete=function(){var e=this.buffer;e&&this.destination.next(e),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.buffer=void 0,this.subscribing=!1},e.prototype.notifyNext=function(){this.openBuffer()},e.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},e.prototype.openBuffer=function(){var t=this.closingSubscription;t&&(this.remove(t),t.unsubscribe());var e,n=this.buffer;this.buffer&&this.destination.next(n),this.buffer=[];try{e=(0,this.closingSelector)()}catch(t){return this.error(t)}t=new P.y,this.closingSubscription=t,this.add(t),this.subscribing=!0,t.add((0,o.tS)(e,new o.zA(this))),this.subscribing=!1},e}(o.gn),D=n(26540),L=n(60685);function z(t){return function(e){return e.lift(new L.ZS(t))}}n(98556),n(44396);var U=n(17815),F=n(37055);function B(){for(var t=[],e=0;e=2;return function(r){return r.pipe((0,Ct.p)((function(e,n){return n===t})),(0,At.s)(1),n?ot(e):It((function(){return new St.k})))}}var kt=n(78274);function Rt(){for(var t=[],e=0;e0&&this._next(t.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},e}(o.gn);function Yt(t){return function(e){return e.lift(new Wt(t))}}var Wt=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Kt(t,this.callback))},t}(),Kt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new P.y(n)),r}return r.C6(e,t),e}(h.v);function $t(t,e){if("function"!=typeof t)throw new TypeError("predicate is not a function");return function(n){return n.lift(new Qt(t,n,!1,e))}}var Qt=function(){function t(t,e,n,r){this.predicate=t,this.source=e,this.yieldIndex=n,this.thisArg=r}return t.prototype.call=function(t,e){return e.subscribe(new Zt(t,this.predicate,this.source,this.yieldIndex,this.thisArg))},t}(),Zt=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;return a.predicate=n,a.source=r,a.yieldIndex=o,a.thisArg=i,a.index=0,a}return r.C6(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete(),this.unsubscribe()},e.prototype._next=function(t){var e=this.predicate,n=this.thisArg,r=this.index++;try{e.call(n||this,t,r,this.source)&&this.notifyComplete(this.yieldIndex?r:t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},e}(h.v);function Jt(t,e){return function(n){return n.lift(new Qt(t,n,!0,e))}}var Xt=n(63242);function te(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?(0,Ct.p)((function(e,n){return t(e,n,r)})):Xt.D,(0,At.s)(1),n?ot(e):It((function(){return new Et.G})))}}var ee=n(40457);function ne(){return function(t){return t.lift(new re)}}var re=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new oe(t))},t}(),oe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.C6(e,t),e.prototype._next=function(t){},e}(h.v);function ie(){return function(t){return t.lift(new ae)}}var ae=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ue(t))},t}(),ue=function(t){function e(e){return t.call(this,e)||this}return r.C6(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype._next=function(t){this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(h.v),ce=n(79058);function se(t){return function(e){return 0===t?(0,ce.I)():e.lift(new le(t))}}var le=function(){function t(t){if(this.total=t,this.total<0)throw new St.k}return t.prototype.call=function(t,e){return e.subscribe(new fe(t,this.total))},t}(),fe=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,o=0;o=2;return function(r){return r.pipe(t?(0,Ct.p)((function(e,n){return t(e,n,r)})):Xt.D,se(1),n?ot(e):It((function(){return new Et.G})))}}function de(t){return function(e){return e.lift(new he(t))}}var he=function(){function t(t){this.value=t}return t.prototype.call=function(t,e){return e.subscribe(new ye(t,this.value))},t}(),ye=function(t){function e(e,n){var r=t.call(this,e)||this;return r.value=n,r}return r.C6(e,t),e.prototype._next=function(t){this.destination.next(this.value)},e}(h.v),ve=n(59038);function me(){return function(t){return t.lift(new ge)}}var ge=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new be(t))},t}(),be=function(t){function e(e){return t.call(this,e)||this}return r.C6(e,t),e.prototype._next=function(t){this.destination.next(ve.E.createNext(t))},e.prototype._error=function(t){var e=this.destination;e.next(ve.E.createError(t)),e.complete()},e.prototype._complete=function(){var t=this.destination;t.next(ve.E.createComplete()),t.complete()},e}(h.v);function _e(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new we(t,e,n))}}var we=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new Se(t,this.accumulator,this.seed,this.hasSeed))},t}(),Se=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i.accumulator=n,i._seed=r,i.hasSeed=o,i.index=0,i}return r.C6(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(t){this.destination.error(t)}this.seed=e,this.destination.next(e)},e}(h.v),Ce=n(7336);function Ee(t,e){return arguments.length>=2?function(n){return(0,Ce.F)(_e(t,e),se(1),ot(e))(n)}:function(e){return(0,Ce.F)(_e((function(e,n,r){return t(e,n,r+1)})),se(1))(e)}}function Ie(t){return Ee("function"==typeof t?function(e,n){return t(e,n)>0?e:n}:function(t,e){return t>e?t:e})}var Oe=n(5475);function Pe(){for(var t=[],e=0;e0?this._next(t.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},e}(o.gn);function Me(t){return Ee("function"==typeof t?function(e,n){return t(e,n)<0?e:n}:function(t,e){return t-1&&(this.count=n-1),e.subscribe(this._unsubscribeAndRecycle())}},e}(h.v);function un(t){return function(e){return e.lift(new cn(t))}}var cn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new sn(t,this.notifier,e))},t}(),sn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.notifier=n,o.source=r,o.sourceIsBeingSubscribedTo=!0,o}return r.C6(e,t),e.prototype.notifyNext=function(){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},e.prototype.notifyComplete=function(){if(!1===this.sourceIsBeingSubscribedTo)return t.prototype.complete.call(this)},e.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return t.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next(void 0)}},e.prototype._unsubscribe=function(){var t=this.notifications,e=this.retriesSubscription;t&&(t.unsubscribe(),this.notifications=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype._unsubscribeAndRecycle=function(){var e=this._unsubscribe;return this._unsubscribe=null,t.prototype._unsubscribeAndRecycle.call(this),this._unsubscribe=e,this},e.prototype.subscribeToRetries=function(){var e;this.notifications=new We.B7;try{e=(0,this.notifier)(this.notifications)}catch(e){return t.prototype.complete.call(this)}this.retries=e,this.retriesSubscription=(0,o.tS)(e,new o.zA(this))},e}(o.gn);function ln(t){return void 0===t&&(t=-1),function(e){return e.lift(new fn(t,e))}}var fn=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new pn(t,this.count,this.source))},t}(),pn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.count=n,o.source=r,o}return r.C6(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return t.prototype.error.call(this,e);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},e}(h.v),dn=n(37405),hn=n(20643);function yn(t){return function(e){return e.lift(new vn(t))}}var vn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new mn(t),r=e.subscribe(n);return r.add((0,o.tS)(this.notifier,new o.zA(n))),r},t}(),mn=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.hasValue=!1,e}return r.C6(e,t),e.prototype._next=function(t){this.value=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},e}(o.gn);function gn(t,e){return void 0===e&&(e=c.b),function(n){return n.lift(new bn(t,e))}}var bn=function(){function t(t,e){this.period=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new _n(t,this.period,this.scheduler))},t}(),_n=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.period=n,o.scheduler=r,o.hasValue=!1,o.add(r.schedule(wn,n,{subscriber:o,period:n})),o}return r.C6(e,t),e.prototype._next=function(t){this.lastValue=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},e}(h.v);function wn(t){var e=t.subscriber,n=t.period;e.notifyNext(),this.schedule(t,n)}function Sn(t,e){return function(n){return n.lift(new Cn(t,e))}}var Cn=function(){function t(t,e){this.compareTo=t,this.comparator=e}return t.prototype.call=function(t,e){return e.subscribe(new En(t,this.compareTo,this.comparator))},t}(),En=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.compareTo=n,o.comparator=r,o._a=[],o._b=[],o._oneComplete=!1,o.destination.add(n.subscribe(new In(e,o))),o}return r.C6(e,t),e.prototype._next=function(t){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(t),this.checkValues())},e.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0,this.unsubscribe()},e.prototype.checkValues=function(){for(var t=this,e=t._a,n=t._b,r=t.comparator;e.length>0&&n.length>0;){var o=e.shift(),i=n.shift(),a=!1;try{a=r?r(o,i):o===i}catch(t){this.destination.error(t)}a||this.emit(!1)}},e.prototype.emit=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype.nextB=function(t){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(t),this.checkValues())},e.prototype.completeB=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},e}(h.v),In=function(t){function e(e,n){var r=t.call(this,e)||this;return r.parent=n,r}return r.C6(e,t),e.prototype._next=function(t){this.parent.nextB(t)},e.prototype._error=function(t){this.parent.error(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.completeB(),this.unsubscribe()},e}(h.v);function On(){return new We.B7}function Pn(){return function(t){return(0,hn.B)()(Ne(On)(t))}}var Tn=n(9099);function An(t){return function(e){return e.lift(new xn(t,e))}}var xn=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new kn(t,this.predicate,this.source))},t}(),kn=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.predicate=n,o.source=r,o.seenValue=!1,o.index=0,o}return r.C6(e,t),e.prototype.applySingleValue=function(t){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=t)},e.prototype._next=function(t){var e=this.index++;this.predicate?this.tryNext(t,e):this.applySingleValue(t)},e.prototype.tryNext=function(t,e){try{this.predicate(t,e,this.source)&&this.applySingleValue(t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){var t=this.destination;this.index>0?(t.next(this.seenValue?this.singleValue:void 0),t.complete()):t.error(new Et.G)},e}(h.v);function Rn(t){return function(e){return e.lift(new Mn(t))}}var Mn=function(){function t(t){this.total=t}return t.prototype.call=function(t,e){return e.subscribe(new jn(t,this.total))},t}(),jn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.C6(e,t),e.prototype._next=function(t){++this.count>this.total&&this.destination.next(t)},e}(h.v);function Nn(t){return function(e){return e.lift(new Dn(t))}}var Dn=function(){function t(t){if(this._skipCount=t,this._skipCount<0)throw new St.k}return t.prototype.call=function(t,e){return 0===this._skipCount?e.subscribe(new h.v(t)):e.subscribe(new Ln(t,this._skipCount))},t}(),Ln=function(t){function e(e,n){var r=t.call(this,e)||this;return r._skipCount=n,r._count=0,r._ring=new Array(n),r}return r.C6(e,t),e.prototype._next=function(t){var e=this._skipCount,n=this._count++;if(n0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,o=this.windows,i=o.length,a=0;a=0&&u%e==0&&!this.closed&&o.shift().complete(),++this.count%e==0&&!this.closed){var c=new We.B7;o.push(c),n.next(c)}},e.prototype._error=function(t){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().complete();this.destination.complete()},e.prototype._unsubscribe=function(){this.count=0,this.windows=null},e}(h.v);function zr(t){var e=c.b,n=null,r=Number.POSITIVE_INFINITY;return(0,b.m)(arguments[3])&&(e=arguments[3]),(0,b.m)(arguments[2])?e=arguments[2]:(0,Yn.k)(arguments[2])&&(r=Number(arguments[2])),(0,b.m)(arguments[1])?e=arguments[1]:(0,Yn.k)(arguments[1])&&(n=Number(arguments[1])),function(o){return o.lift(new Ur(t,n,r,e))}}var Ur=function(){function t(t,e,n,r){this.windowTimeSpan=t,this.windowCreationInterval=e,this.maxWindowSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new Br(t,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},t}(),Fr=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._numberOfNextedValues=0,e}return r.C6(e,t),e.prototype.next=function(e){this._numberOfNextedValues++,t.prototype.next.call(this,e)},Object.defineProperty(e.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),e}(We.B7),Br=function(t){function e(e,n,r,o,i){var a=t.call(this,e)||this;a.destination=e,a.windowTimeSpan=n,a.windowCreationInterval=r,a.maxWindowSize=o,a.scheduler=i,a.windows=[];var u=a.openWindow();if(null!==r&&r>=0){var c={subscriber:a,window:u,context:null},s={windowTimeSpan:n,windowCreationInterval:r,subscriber:a,scheduler:i};a.add(i.schedule(Gr,n,c)),a.add(i.schedule(Vr,r,s))}else{var l={subscriber:a,window:u,windowTimeSpan:n};a.add(i.schedule(qr,n,l))}return a}return r.C6(e,t),e.prototype._next=function(t){for(var e=this.windows,n=e.length,r=0;r=this.maxWindowSize&&this.closeWindow(o))}},e.prototype._error=function(t){for(var e=this.windows;e.length>0;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){for(var t=this.windows;t.length>0;){var e=t.shift();e.closed||e.complete()}this.destination.complete()},e.prototype.openWindow=function(){var t=new Fr;return this.windows.push(t),this.destination.next(t),t},e.prototype.closeWindow=function(t){t.complete();var e=this.windows;e.splice(e.indexOf(t),1)},e}(h.v);function qr(t){var e=t.subscriber,n=t.windowTimeSpan,r=t.window;r&&e.closeWindow(r),t.window=e.openWindow(),this.schedule(t,n)}function Vr(t){var e=t.windowTimeSpan,n=t.subscriber,r=t.scheduler,o=t.windowCreationInterval,i=n.openWindow(),a=this,u={action:a,subscription:null},c={subscriber:n,window:i,context:u};u.subscription=r.schedule(Gr,e,c),a.add(u.subscription),a.schedule(t,o)}function Gr(t){var e=t.subscriber,n=t.window,r=t.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),e.closeWindow(n)}function Hr(t,e){return function(n){return n.lift(new Yr(t,e))}}var Yr=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new Wr(t,this.openings,this.closingSelector))},t}(),Wr=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.openings=n,o.closingSelector=r,o.contexts=[],o.add(o.openSubscription=(0,T.F)(o,n,n)),o}return r.C6(e,t),e.prototype._next=function(t){var e=this.contexts;if(e)for(var n=e.length,r=0;r0){var o=r.indexOf(n);-1!==o&&r.splice(o,1)}},e.prototype.notifyComplete=function(){},e.prototype._next=function(t){if(0===this.toRespond.length){var e=[t].concat(this.values);this.project?this._tryProject(e):this.destination.next(e)}},e.prototype._tryProject=function(t){var e;try{e=this.project.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(A.E),to=n(28124);function eo(){for(var t=[],e=0;e{"use strict";n.d(e,{C6:()=>o}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var r=function(t,e){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},r(t,e)};function o(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}},96150:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(21894),n(13521),n(25766),n(92947),t.exports=function(t,e,n,o){var i=n?n.call(o,t,e):void 0;if(void 0!==i)return!!i;if(t===e)return!0;if("object"!==r(t)||!t||"object"!==r(e)||!e)return!1;var a=Object.keys(t),u=Object.keys(e);if(a.length!==u.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(e),s=0;s{"use strict";n(47818),n(44396),t.exports=function(t,e){if("string"!=typeof t||"string"!=typeof e)throw new TypeError("Expected the arguments to be of type `string`");if(""===e)return[t];var n=t.indexOf(e);return-1===n?[t]:[t.slice(0,n),t.slice(n+e.length)]}},23081:(t,e,n)=>{"use strict";n(13521),n(88315),n(53618),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}},35476:(t,e,n)=>{var r=n(11055),o=n(79269),i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not a function")}},68634:(t,e,n)=>{var r=n(11547),o=n(79269),i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not a constructor")}},1520:(t,e,n)=>{var r=n(11055),o=String,i=TypeError;t.exports=function(t){if("object"==typeof t||r(t))return t;throw i("Can't set "+o(t)+" as a prototype")}},44595:(t,e,n)=>{var r=n(39189),o=n(32814),i=n(59143).f,a=r("unscopables"),u=Array.prototype;null==u[a]&&i(u,a,{configurable:!0,value:o(null)}),t.exports=function(t){u[a][t]=!0}},78839:(t,e,n)=>{"use strict";var r=n(65877).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},37809:(t,e,n)=>{var r=n(47931),o=TypeError;t.exports=function(t,e){if(r(e,t))return t;throw o("Incorrect invocation")}},90649:(t,e,n)=>{var r=n(96692),o=String,i=TypeError;t.exports=function(t){if(r(t))return t;throw i(o(t)+" is not an object")}},69141:t=>{t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},65642:(t,e,n)=>{var r=n(79061);t.exports=r((function(){if("function"==typeof ArrayBuffer){var t=new ArrayBuffer(8);Object.isExtensible(t)&&Object.defineProperty(t,"a",{value:8})}}))},70668:(t,e,n)=>{"use strict";var r=n(21833),o=n(38982),i=n(4426),a=n(69141),u=n(92684),c=n(69193),s=n(61548),l=n(14101),f=n(79061),p=n(37809),d=n(91129),h=n(99536),y=n(2042),v=n(13228),m=n(52473),g=n(26213),b=n(47210).f,_=n(70419),w=n(10301),S=n(49233),C=n(58319),E=u.PROPER,I=u.CONFIGURABLE,O="ArrayBuffer",P="DataView",T="prototype",A="Wrong index",x=C.getterFor(O),k=C.getterFor(P),R=C.set,M=r[O],j=M,N=j&&j[T],D=r[P],L=D&&D[T],z=Object.prototype,U=r.Array,F=r.RangeError,B=o(_),q=o([].reverse),V=v.pack,G=v.unpack,H=function(t){return[255&t]},Y=function(t){return[255&t,t>>8&255]},W=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},K=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},$=function(t){return V(t,23,4)},Q=function(t){return V(t,52,8)},Z=function(t,e,n){s(t[T],e,{configurable:!0,get:function(){return n(this)[e]}})},J=function(t,e,n,r){var o=y(n),i=k(t);if(o+e>i.byteLength)throw F(A);var a=i.bytes,u=o+i.byteOffset,c=w(a,u,u+e);return r?c:q(c)},X=function(t,e,n,r,o,i){var a=y(n),u=k(t);if(a+e>u.byteLength)throw F(A);for(var c=u.bytes,s=a+u.byteOffset,l=r(+o),f=0;frt;)(et=nt[rt++])in j||c(j,et,M[et]);N.constructor=j}g&&m(L)!==z&&g(L,z);var ot=new D(new j(2)),it=o(L.setInt8);ot.setInt8(0,2147483648),ot.setInt8(1,2147483649),!ot.getInt8(0)&&ot.getInt8(1)||l(L,{setInt8:function(t,e){it(this,t,e<<24>>24)},setUint8:function(t,e){it(this,t,e<<24>>24)}},{unsafe:!0})}else N=(j=function(t){p(this,N);var e=y(t);R(this,{type:O,bytes:B(U(e),0),byteLength:e}),i||(this.byteLength=e,this.detached=!1)})[T],L=(D=function(t,e,n){p(this,L),p(t,N);var r=x(t),o=r.byteLength,a=d(e);if(a<0||a>o)throw F("Wrong offset");if(a+(n=void 0===n?o-a:h(n))>o)throw F("Wrong length");R(this,{type:P,buffer:t,byteLength:n,byteOffset:a,bytes:r.bytes}),i||(this.buffer=t,this.byteLength=n,this.byteOffset=a)})[T],i&&(Z(j,"byteLength",x),Z(D,"buffer",k),Z(D,"byteLength",k),Z(D,"byteOffset",k)),l(L,{getInt8:function(t){return J(this,1,t)[0]<<24>>24},getUint8:function(t){return J(this,1,t)[0]},getInt16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return e[1]<<8|e[0]},getInt32:function(t){return K(J(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return K(J(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return G(J(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return G(J(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,e){X(this,1,t,H,e)},setUint8:function(t,e){X(this,1,t,H,e)},setInt16:function(t,e){X(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,e){X(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,e){X(this,4,t,W,e,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,e){X(this,4,t,W,e,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,e){X(this,4,t,$,e,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,e){X(this,8,t,Q,e,arguments.length>2?arguments[2]:void 0)}});S(j,O),S(D,P),t.exports={ArrayBuffer:j,DataView:D}},70419:(t,e,n)=>{"use strict";var r=n(50775),o=n(79036),i=n(12244);t.exports=function(t){for(var e=r(this),n=i(e),a=arguments.length,u=o(a>1?arguments[1]:void 0,n),c=a>2?arguments[2]:void 0,s=void 0===c?n:o(c,n);s>u;)e[u++]=t;return e}},9877:(t,e,n)=>{"use strict";var r=n(31567).forEach,o=n(46644)("forEach");t.exports=o?[].forEach:function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}},36658:(t,e,n)=>{"use strict";var r=n(67302),o=n(44931),i=n(50775),a=n(33809),u=n(77847),c=n(11547),s=n(12244),l=n(25762),f=n(81963),p=n(16421),d=Array;t.exports=function(t){var e=i(t),n=c(this),h=arguments.length,y=h>1?arguments[1]:void 0,v=void 0!==y;v&&(y=r(y,h>2?arguments[2]:void 0));var m,g,b,_,w,S,C=p(e),E=0;if(!C||this===d&&u(C))for(m=s(e),g=n?new this(m):d(m);m>E;E++)S=v?y(e[E],E):e[E],l(g,E,S);else for(w=(_=f(e,C)).next,g=n?new this:[];!(b=o(w,_)).done;E++)S=v?a(_,y,[b.value,E],!0):b.value,l(g,E,S);return g.length=E,g}},20895:(t,e,n)=>{var r=n(4395),o=n(79036),i=n(12244),a=function(t){return function(e,n,a){var u,c=r(e),s=i(c),l=o(a,s);if(t&&n!=n){for(;s>l;)if((u=c[l++])!=u)return!0}else for(;s>l;l++)if((t||l in c)&&c[l]===n)return t||l||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},31567:(t,e,n)=>{var r=n(67302),o=n(38982),i=n(7461),a=n(50775),u=n(12244),c=n(88627),s=o([].push),l=function(t){var e=1==t,n=2==t,o=3==t,l=4==t,f=6==t,p=7==t,d=5==t||f;return function(h,y,v,m){for(var g,b,_=a(h),w=i(_),S=r(y,v),C=u(w),E=0,I=m||c,O=e?I(h,C):n||p?I(h,0):void 0;C>E;E++)if((d||E in w)&&(b=S(g=w[E],E,_),t))if(e)O[E]=b;else if(b)switch(t){case 3:return!0;case 5:return g;case 6:return E;case 2:s(O,g)}else switch(t){case 4:return!1;case 7:s(O,g)}return f?-1:o||l?l:O}};t.exports={forEach:l(0),map:l(1),filter:l(2),some:l(3),every:l(4),find:l(5),findIndex:l(6),filterReject:l(7)}},37041:(t,e,n)=>{"use strict";var r=n(33247),o=n(4395),i=n(91129),a=n(12244),u=n(46644),c=Math.min,s=[].lastIndexOf,l=!!s&&1/[1].lastIndexOf(1,-0)<0,f=u("lastIndexOf"),p=l||!f;t.exports=p?function(t){if(l)return r(s,this,arguments)||0;var e=o(this),n=a(e),u=n-1;for(arguments.length>1&&(u=c(u,i(arguments[1]))),u<0&&(u=n+u);u>=0;u--)if(u in e&&e[u]===t)return u||0;return-1}:s},20423:(t,e,n)=>{var r=n(79061),o=n(39189),i=n(36918),a=o("species");t.exports=function(t){return i>=51||!r((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},46644:(t,e,n)=>{"use strict";var r=n(79061);t.exports=function(t,e){var n=[][t];return!!n&&r((function(){n.call(null,e||function(){return 1},1)}))}},41909:(t,e,n)=>{"use strict";var r=n(4426),o=n(57886),i=TypeError,a=Object.getOwnPropertyDescriptor,u=r&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(t){return t instanceof TypeError}}();t.exports=u?function(t,e){if(o(t)&&!a(t,"length").writable)throw i("Cannot set read only .length");return t.length=e}:function(t,e){return t.length=e}},10301:(t,e,n)=>{var r=n(79036),o=n(12244),i=n(25762),a=Array,u=Math.max;t.exports=function(t,e,n){for(var c=o(t),s=r(e,c),l=r(void 0===n?c:n,c),f=a(u(l-s,0)),p=0;s{var r=n(38982);t.exports=r([].slice)},84326:(t,e,n)=>{var r=n(10301),o=Math.floor,i=function(t,e){var n=t.length,c=o(n/2);return n<8?a(t,e):u(t,i(r(t,0,c),e),i(r(t,c),e),e)},a=function(t,e){for(var n,r,o=t.length,i=1;i0;)t[r]=t[--r];r!==i++&&(t[r]=n)}return t},u=function(t,e,n,r){for(var o=e.length,i=n.length,a=0,u=0;a{var r=n(57886),o=n(11547),i=n(96692),a=n(39189)("species"),u=Array;t.exports=function(t){var e;return r(t)&&(e=t.constructor,(o(e)&&(e===u||r(e.prototype))||i(e)&&null===(e=e[a]))&&(e=void 0)),void 0===e?u:e}},88627:(t,e,n)=>{var r=n(98531);t.exports=function(t,e){return new(r(t))(0===e?0:e)}},33809:(t,e,n)=>{var r=n(90649),o=n(78309);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){o(t,"throw",e)}}},25542:(t,e,n)=>{var r=n(39189)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[r]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var n=!1;try{var i={};i[r]=function(){return{next:function(){return{done:n=!0}}}},t(i)}catch(t){}return n}},17170:(t,e,n)=>{var r=n(38982),o=r({}.toString),i=r("".slice);t.exports=function(t){return i(o(t),8,-1)}},75493:(t,e,n)=>{var r=n(13878),o=n(11055),i=n(17170),a=n(39189)("toStringTag"),u=Object,c="Arguments"==i(function(){return arguments}());t.exports=r?i:function(t){var e,n,r;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=u(t),a))?n:c?i(e):"Object"==(r=i(e))&&o(e.callee)?"Arguments":r}},49720:(t,e,n)=>{"use strict";var r=n(32814),o=n(61548),i=n(14101),a=n(67302),u=n(37809),c=n(40899),s=n(4846),l=n(49626),f=n(42579),p=n(18807),d=n(4426),h=n(89277).fastKey,y=n(58319),v=y.set,m=y.getterFor;t.exports={getConstructor:function(t,e,n,l){var f=t((function(t,o){u(t,p),v(t,{type:e,index:r(null),first:void 0,last:void 0,size:0}),d||(t.size=0),c(o)||s(o,t[l],{that:t,AS_ENTRIES:n})})),p=f.prototype,y=m(e),g=function(t,e,n){var r,o,i=y(t),a=b(t,e);return a?a.value=n:(i.last=a={index:o=h(e,!0),key:e,value:n,previous:r=i.last,next:void 0,removed:!1},i.first||(i.first=a),r&&(r.next=a),d?i.size++:t.size++,"F"!==o&&(i.index[o]=a)),t},b=function(t,e){var n,r=y(t),o=h(e);if("F"!==o)return r.index[o];for(n=r.first;n;n=n.next)if(n.key==e)return n};return i(p,{clear:function(){for(var t=y(this),e=t.index,n=t.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete e[n.index],n=n.next;t.first=t.last=void 0,d?t.size=0:this.size=0},delete:function(t){var e=this,n=y(e),r=b(e,t);if(r){var o=r.next,i=r.previous;delete n.index[r.index],r.removed=!0,i&&(i.next=o),o&&(o.previous=i),n.first==r&&(n.first=o),n.last==r&&(n.last=i),d?n.size--:e.size--}return!!r},forEach:function(t){for(var e,n=y(this),r=a(t,arguments.length>1?arguments[1]:void 0);e=e?e.next:n.first;)for(r(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!b(this,t)}}),i(p,n?{get:function(t){var e=b(this,t);return e&&e.value},set:function(t,e){return g(this,0===t?0:t,e)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),d&&o(p,"size",{configurable:!0,get:function(){return y(this).size}}),f},setStrong:function(t,e,n){var r=e+" Iterator",o=m(e),i=m(r);l(t,e,(function(t,e){v(this,{type:r,target:t,state:o(t),kind:e,last:void 0})}),(function(){for(var t=i(this),e=t.kind,n=t.last;n&&n.removed;)n=n.previous;return t.target&&(t.last=n=n?n.next:t.state.first)?f("keys"==e?n.key:"values"==e?n.value:[n.key,n.value],!1):(t.target=void 0,f(void 0,!0))}),n?"entries":"values",!n,!0),p(e)}}},42715:(t,e,n)=>{"use strict";var r=n(38982),o=n(14101),i=n(89277).getWeakData,a=n(37809),u=n(90649),c=n(40899),s=n(96692),l=n(4846),f=n(31567),p=n(34863),d=n(58319),h=d.set,y=d.getterFor,v=f.find,m=f.findIndex,g=r([].splice),b=0,_=function(t){return t.frozen||(t.frozen=new w)},w=function(){this.entries=[]},S=function(t,e){return v(t.entries,(function(t){return t[0]===e}))};w.prototype={get:function(t){var e=S(this,t);if(e)return e[1]},has:function(t){return!!S(this,t)},set:function(t,e){var n=S(this,t);n?n[1]=e:this.entries.push([t,e])},delete:function(t){var e=m(this.entries,(function(e){return e[0]===t}));return~e&&g(this.entries,e,1),!!~e}},t.exports={getConstructor:function(t,e,n,r){var f=t((function(t,o){a(t,d),h(t,{type:e,id:b++,frozen:void 0}),c(o)||l(o,t[r],{that:t,AS_ENTRIES:n})})),d=f.prototype,v=y(e),m=function(t,e,n){var r=v(t),o=i(u(e),!0);return!0===o?_(r).set(e,n):o[r.id]=n,t};return o(d,{delete:function(t){var e=v(this);if(!s(t))return!1;var n=i(t);return!0===n?_(e).delete(t):n&&p(n,e.id)&&delete n[e.id]},has:function(t){var e=v(this);if(!s(t))return!1;var n=i(t);return!0===n?_(e).has(t):n&&p(n,e.id)}}),o(d,n?{get:function(t){var e=v(this);if(s(t)){var n=i(t);return!0===n?_(e).get(t):n?n[e.id]:void 0}},set:function(t,e){return m(this,t,e)}}:{add:function(t){return m(this,t,!0)}}),f}}},35365:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(38982),a=n(96942),u=n(92446),c=n(89277),s=n(4846),l=n(37809),f=n(11055),p=n(40899),d=n(96692),h=n(79061),y=n(25542),v=n(49233),m=n(86953);t.exports=function(t,e,n){var g=-1!==t.indexOf("Map"),b=-1!==t.indexOf("Weak"),_=g?"set":"add",w=o[t],S=w&&w.prototype,C=w,E={},I=function(t){var e=i(S[t]);u(S,t,"add"==t?function(t){return e(this,0===t?0:t),this}:"delete"==t?function(t){return!(b&&!d(t))&&e(this,0===t?0:t)}:"get"==t?function(t){return b&&!d(t)?void 0:e(this,0===t?0:t)}:"has"==t?function(t){return!(b&&!d(t))&&e(this,0===t?0:t)}:function(t,n){return e(this,0===t?0:t,n),this})};if(a(t,!f(w)||!(b||S.forEach&&!h((function(){(new w).entries().next()})))))C=n.getConstructor(e,t,g,_),c.enable();else if(a(t,!0)){var O=new C,P=O[_](b?{}:-0,1)!=O,T=h((function(){O.has(1)})),A=y((function(t){new w(t)})),x=!b&&h((function(){for(var t=new w,e=5;e--;)t[_](e,e);return!t.has(-0)}));A||((C=e((function(t,e){l(t,S);var n=m(new w,t,C);return p(e)||s(e,n[_],{that:n,AS_ENTRIES:g}),n}))).prototype=S,S.constructor=C),(T||x)&&(I("delete"),I("has"),g&&I("get")),(x||P)&&I(_),b&&S.clear&&delete S.clear}return E[t]=C,r({global:!0,constructor:!0,forced:C!=w},E),v(C,t),b||n.setStrong(C,t,g),C}},14938:(t,e,n)=>{var r=n(34863),o=n(8517),i=n(77637),a=n(59143);t.exports=function(t,e,n){for(var u=o(e),c=a.f,s=i.f,l=0;l{var r=n(39189)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,"/./"[t](e)}catch(t){}}return!1}},16797:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},68662:(t,e,n)=>{var r=n(38982),o=n(29412),i=n(96641),a=/"/g,u=r("".replace);t.exports=function(t,e,n,r){var c=i(o(t)),s="<"+e;return""!==n&&(s+=" "+n+'="'+u(i(r),a,""")+'"'),s+">"+c+""}},42579:t=>{t.exports=function(t,e){return{value:t,done:e}}},69193:(t,e,n)=>{var r=n(4426),o=n(59143),i=n(52302);t.exports=r?function(t,e,n){return o.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},52302:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},25762:(t,e,n)=>{"use strict";var r=n(50243),o=n(59143),i=n(52302);t.exports=function(t,e,n){var a=r(e);a in t?o.f(t,a,i(0,n)):t[a]=n}},55362:(t,e,n)=>{"use strict";var r=n(90649),o=n(2272),i=TypeError;t.exports=function(t){if(r(this),"string"===t||"default"===t)t="string";else if("number"!==t)throw i("Incorrect hint");return o(this,t)}},61548:(t,e,n)=>{var r=n(58245),o=n(59143);t.exports=function(t,e,n){return n.get&&r(n.get,e,{getter:!0}),n.set&&r(n.set,e,{setter:!0}),o.f(t,e,n)}},92446:(t,e,n)=>{var r=n(11055),o=n(59143),i=n(58245),a=n(11891);t.exports=function(t,e,n,u){u||(u={});var c=u.enumerable,s=void 0!==u.name?u.name:e;if(r(n)&&i(n,s,u),u.global)c?t[e]=n:a(e,n);else{try{u.unsafe?t[e]&&(c=!0):delete t[e]}catch(t){}c?t[e]=n:o.f(t,e,{value:n,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return t}},14101:(t,e,n)=>{var r=n(92446);t.exports=function(t,e,n){for(var o in e)r(t,o,e[o],n);return t}},11891:(t,e,n)=>{var r=n(21833),o=Object.defineProperty;t.exports=function(t,e){try{o(r,t,{value:e,configurable:!0,writable:!0})}catch(n){r[t]=e}return e}},87472:(t,e,n)=>{"use strict";var r=n(79269),o=TypeError;t.exports=function(t,e){if(!delete t[e])throw o("Cannot delete property "+r(e)+" of "+r(t))}},4426:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},36185:t=>{var e="object"==typeof document&&document.all,n=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:n}},46349:(t,e,n)=>{var r=n(21833),o=n(96692),i=r.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},68655:t=>{var e=TypeError;t.exports=function(t){if(t>9007199254740991)throw e("Maximum allowed index exceeded");return t}},4774:t=>{t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},4474:(t,e,n)=>{var r=n(46349)("span").classList,o=r&&r.constructor&&r.constructor.prototype;t.exports=o===Object.prototype?void 0:o},27496:(t,e,n)=>{var r=n(60514).match(/firefox\/(\d+)/i);t.exports=!!r&&+r[1]},43704:(t,e,n)=>{var r=n(99574),o=n(36954);t.exports=!r&&!o&&"object"==typeof window&&"object"==typeof document},99574:t=>{t.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},36928:(t,e,n)=>{var r=n(60514);t.exports=/MSIE|Trident/.test(r)},52134:(t,e,n)=>{var r=n(60514);t.exports=/ipad|iphone|ipod/i.test(r)&&"undefined"!=typeof Pebble},19997:(t,e,n)=>{var r=n(60514);t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(r)},36954:(t,e,n)=>{var r=n(17170);t.exports="undefined"!=typeof process&&"process"==r(process)},89299:(t,e,n)=>{var r=n(60514);t.exports=/web0s(?!.*chrome)/i.test(r)},60514:t=>{t.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},36918:(t,e,n)=>{var r,o,i=n(21833),a=n(60514),u=i.process,c=i.Deno,s=u&&u.versions||c&&c.version,l=s&&s.v8;l&&(o=(r=l.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!o&&a&&(!(r=a.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=a.match(/Chrome\/(\d+)/))&&(o=+r[1]),t.exports=o},53522:(t,e,n)=>{var r=n(60514).match(/AppleWebKit\/(\d+)\./);t.exports=!!r&&+r[1]},39513:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},58288:(t,e,n)=>{var r=n(21833),o=n(77637).f,i=n(69193),a=n(92446),u=n(11891),c=n(14938),s=n(96942);t.exports=function(t,e){var n,l,f,p,d,h=t.target,y=t.global,v=t.stat;if(n=y?r:v?r[h]||u(h,{}):(r[h]||{}).prototype)for(l in e){if(p=e[l],f=t.dontCallGetSet?(d=o(n,l))&&d.value:n[l],!s(y?l:h+(v?".":"#")+l,t.forced)&&void 0!==f){if(typeof p==typeof f)continue;c(p,f)}(t.sham||f&&f.sham)&&i(p,"sham",!0),a(n,l,p,t)}}},79061:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},35146:(t,e,n)=>{"use strict";n(18489);var r=n(46526),o=n(92446),i=n(74989),a=n(79061),u=n(39189),c=n(69193),s=u("species"),l=RegExp.prototype;t.exports=function(t,e,n,f){var p=u(t),d=!a((function(){var e={};return e[p]=function(){return 7},7!=""[t](e)})),h=d&&!a((function(){var e=!1,n=/a/;return"split"===t&&((n={}).constructor={},n.constructor[s]=function(){return n},n.flags="",n[p]=/./[p]),n.exec=function(){return e=!0,null},n[p](""),!e}));if(!d||!h||n){var y=r(/./[p]),v=e(p,""[t],(function(t,e,n,o,a){var u=r(t),c=e.exec;return c===i||c===l.exec?d&&!a?{done:!0,value:y(e,n,o)}:{done:!0,value:u(n,e,o)}:{done:!1}}));o(String.prototype,t,v[0]),o(l,p,v[1])}f&&c(l[p],"sham",!0)}},96493:(t,e,n)=>{"use strict";var r=n(57886),o=n(12244),i=n(68655),a=n(67302),u=function(t,e,n,c,s,l,f,p){for(var d,h,y=s,v=0,m=!!f&&a(f,p);v0&&r(d)?(h=o(d),y=u(t,e,d,h,y,l-1)-1):(i(y+1),t[y]=d),y++),v++;return y};t.exports=u},1566:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},33247:(t,e,n)=>{var r=n(8470),o=Function.prototype,i=o.apply,a=o.call;t.exports="object"==typeof Reflect&&Reflect.apply||(r?a.bind(i):function(){return a.apply(i,arguments)})},67302:(t,e,n)=>{var r=n(46526),o=n(35476),i=n(8470),a=r(r.bind);t.exports=function(t,e){return o(t),void 0===e?t:i?a(t,e):function(){return t.apply(e,arguments)}}},8470:(t,e,n)=>{var r=n(79061);t.exports=!r((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},44931:(t,e,n)=>{var r=n(8470),o=Function.prototype.call;t.exports=r?o.bind(o):function(){return o.apply(o,arguments)}},92684:(t,e,n)=>{var r=n(4426),o=n(34863),i=Function.prototype,a=r&&Object.getOwnPropertyDescriptor,u=o(i,"name"),c=u&&"something"===function(){}.name,s=u&&(!r||r&&a(i,"name").configurable);t.exports={EXISTS:u,PROPER:c,CONFIGURABLE:s}},67652:(t,e,n)=>{var r=n(38982),o=n(35476);t.exports=function(t,e,n){try{return r(o(Object.getOwnPropertyDescriptor(t,e)[n]))}catch(t){}}},46526:(t,e,n)=>{var r=n(17170),o=n(38982);t.exports=function(t){if("Function"===r(t))return o(t)}},38982:(t,e,n)=>{var r=n(8470),o=Function.prototype,i=o.call,a=r&&o.bind.bind(i,i);t.exports=r?a:function(t){return function(){return i.apply(t,arguments)}}},78797:(t,e,n)=>{var r=n(21833),o=n(11055);t.exports=function(t,e){return arguments.length<2?(n=r[t],o(n)?n:void 0):r[t]&&r[t][e];var n}},16421:(t,e,n)=>{var r=n(75493),o=n(4224),i=n(40899),a=n(45347),u=n(39189)("iterator");t.exports=function(t){if(!i(t))return o(t,u)||o(t,"@@iterator")||a[r(t)]}},81963:(t,e,n)=>{var r=n(44931),o=n(35476),i=n(90649),a=n(79269),u=n(16421),c=TypeError;t.exports=function(t,e){var n=arguments.length<2?u(t):e;if(o(n))return i(r(n,t));throw c(a(t)+" is not iterable")}},54875:(t,e,n)=>{var r=n(38982),o=n(57886),i=n(11055),a=n(17170),u=n(96641),c=r([].push);t.exports=function(t){if(i(t))return t;if(o(t)){for(var e=t.length,n=[],r=0;r{var r=n(35476),o=n(40899);t.exports=function(t,e){var n=t[e];return o(n)?void 0:r(n)}},34032:(t,e,n)=>{var r=n(38982),o=n(50775),i=Math.floor,a=r("".charAt),u=r("".replace),c=r("".slice),s=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,l=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,n,r,f,p){var d=n+t.length,h=r.length,y=l;return void 0!==f&&(f=o(f),y=s),u(p,y,(function(o,u){var s;switch(a(u,0)){case"$":return"$";case"&":return t;case"`":return c(e,0,n);case"'":return c(e,d);case"<":s=f[c(u,1,-1)];break;default:var l=+u;if(0===l)return o;if(l>h){var p=i(l/10);return 0===p?o:p<=h?void 0===r[p-1]?a(u,1):r[p-1]+a(u,1):o}s=r[l-1]}return void 0===s?"":s}))}},21833:function(t,e,n){var r=function(t){return t&&t.Math==Math&&t};t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n.g&&n.g)||function(){return this}()||this||Function("return this")()},34863:(t,e,n)=>{var r=n(38982),o=n(50775),i=r({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return i(o(t),e)}},43343:t=>{t.exports={}},69991:t=>{t.exports=function(t,e){try{1==arguments.length?console.error(t):console.error(t,e)}catch(t){}}},75527:(t,e,n)=>{var r=n(78797);t.exports=r("document","documentElement")},99667:(t,e,n)=>{var r=n(4426),o=n(79061),i=n(46349);t.exports=!r&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},13228:t=>{var e=Array,n=Math.abs,r=Math.pow,o=Math.floor,i=Math.log,a=Math.LN2;t.exports={pack:function(t,u,c){var s,l,f,p=e(c),d=8*c-u-1,h=(1<>1,v=23===u?r(2,-24)-r(2,-77):0,m=t<0||0===t&&1/t<0?1:0,g=0;for((t=n(t))!=t||t===1/0?(l=t!=t?1:0,s=h):(s=o(i(t)/a),t*(f=r(2,-s))<1&&(s--,f*=2),(t+=s+y>=1?v/f:v*r(2,1-y))*f>=2&&(s++,f/=2),s+y>=h?(l=0,s=h):s+y>=1?(l=(t*f-1)*r(2,u),s+=y):(l=t*r(2,y-1)*r(2,u),s=0));u>=8;)p[g++]=255&l,l/=256,u-=8;for(s=s<0;)p[g++]=255&s,s/=256,d-=8;return p[--g]|=128*m,p},unpack:function(t,e){var n,o=t.length,i=8*o-e-1,a=(1<>1,c=i-7,s=o-1,l=t[s--],f=127&l;for(l>>=7;c>0;)f=256*f+t[s--],c-=8;for(n=f&(1<<-c)-1,f>>=-c,c+=e;c>0;)n=256*n+t[s--],c-=8;if(0===f)f=1-u;else{if(f===a)return n?NaN:l?-1/0:1/0;n+=r(2,e),f-=u}return(l?-1:1)*n*r(2,f-e)}}},7461:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(17170),a=Object,u=r("".split);t.exports=o((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==i(t)?u(t,""):a(t)}:a},86953:(t,e,n)=>{var r=n(11055),o=n(96692),i=n(26213);t.exports=function(t,e,n){var a,u;return i&&r(a=e.constructor)&&a!==n&&o(u=a.prototype)&&u!==n.prototype&&i(t,u),t}},27728:(t,e,n)=>{var r=n(38982),o=n(11055),i=n(47099),a=r(Function.toString);o(i.inspectSource)||(i.inspectSource=function(t){return a(t)}),t.exports=i.inspectSource},89277:(t,e,n)=>{var r=n(58288),o=n(38982),i=n(43343),a=n(96692),u=n(34863),c=n(59143).f,s=n(47210),l=n(83744),f=n(81278),p=n(64550),d=n(1566),h=!1,y=p("meta"),v=0,m=function(t){c(t,y,{value:{objectID:"O"+v++,weakData:{}}})},g=t.exports={enable:function(){g.enable=function(){},h=!0;var t=s.f,e=o([].splice),n={};n[y]=1,t(n).length&&(s.f=function(n){for(var r=t(n),o=0,i=r.length;o{var r,o,i,a=n(74528),u=n(21833),c=n(96692),s=n(69193),l=n(34863),f=n(47099),p=n(40693),d=n(43343),h="Object already initialized",y=u.TypeError,v=u.WeakMap;if(a||f.state){var m=f.state||(f.state=new v);m.get=m.get,m.has=m.has,m.set=m.set,r=function(t,e){if(m.has(t))throw y(h);return e.facade=t,m.set(t,e),e},o=function(t){return m.get(t)||{}},i=function(t){return m.has(t)}}else{var g=p("state");d[g]=!0,r=function(t,e){if(l(t,g))throw y(h);return e.facade=t,s(t,g,e),e},o=function(t){return l(t,g)?t[g]:{}},i=function(t){return l(t,g)}}t.exports={set:r,get:o,has:i,enforce:function(t){return i(t)?o(t):r(t,{})},getterFor:function(t){return function(e){var n;if(!c(e)||(n=o(e)).type!==t)throw y("Incompatible receiver, "+t+" required");return n}}}},77847:(t,e,n)=>{var r=n(39189),o=n(45347),i=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},57886:(t,e,n)=>{var r=n(17170);t.exports=Array.isArray||function(t){return"Array"==r(t)}},11055:(t,e,n)=>{var r=n(36185),o=r.all;t.exports=r.IS_HTMLDDA?function(t){return"function"==typeof t||t===o}:function(t){return"function"==typeof t}},11547:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(11055),a=n(75493),u=n(78797),c=n(27728),s=function(){},l=[],f=u("Reflect","construct"),p=/^\s*(?:class|function)\b/,d=r(p.exec),h=!p.exec(s),y=function(t){if(!i(t))return!1;try{return f(s,l,t),!0}catch(t){return!1}},v=function(t){if(!i(t))return!1;switch(a(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!d(p,c(t))}catch(t){return!0}};v.sham=!0,t.exports=!f||o((function(){var t;return y(y.call)||!y(Object)||!y((function(){t=!0}))||t}))?v:y},96942:(t,e,n)=>{var r=n(79061),o=n(11055),i=/#|\.prototype\./,a=function(t,e){var n=c[u(t)];return n==l||n!=s&&(o(e)?r(e):!!e)},u=a.normalize=function(t){return String(t).replace(i,".").toLowerCase()},c=a.data={},s=a.NATIVE="N",l=a.POLYFILL="P";t.exports=a},40899:t=>{t.exports=function(t){return null==t}},96692:(t,e,n)=>{var r=n(11055),o=n(36185),i=o.all;t.exports=o.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:r(t)||t===i}:function(t){return"object"==typeof t?null!==t:r(t)}},59785:t=>{t.exports=!1},16030:(t,e,n)=>{var r=n(96692),o=n(17170),i=n(39189)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[i])?!!e:"RegExp"==o(t))}},30907:(t,e,n)=>{var r=n(78797),o=n(11055),i=n(47931),a=n(92010),u=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=r("Symbol");return o(e)&&i(e.prototype,u(t))}},4846:(t,e,n)=>{var r=n(67302),o=n(44931),i=n(90649),a=n(79269),u=n(77847),c=n(12244),s=n(47931),l=n(81963),f=n(16421),p=n(78309),d=TypeError,h=function(t,e){this.stopped=t,this.result=e},y=h.prototype;t.exports=function(t,e,n){var v,m,g,b,_,w,S,C=n&&n.that,E=!(!n||!n.AS_ENTRIES),I=!(!n||!n.IS_RECORD),O=!(!n||!n.IS_ITERATOR),P=!(!n||!n.INTERRUPTED),T=r(e,C),A=function(t){return v&&p(v,"normal",t),new h(!0,t)},x=function(t){return E?(i(t),P?T(t[0],t[1],A):T(t[0],t[1])):P?T(t,A):T(t)};if(I)v=t.iterator;else if(O)v=t;else{if(!(m=f(t)))throw d(a(t)+" is not iterable");if(u(m)){for(g=0,b=c(t);b>g;g++)if((_=x(t[g]))&&s(y,_))return _;return new h(!1)}v=l(t,m)}for(w=I?t.next:v.next;!(S=o(w,v)).done;){try{_=x(S.value)}catch(t){p(v,"throw",t)}if("object"==typeof _&&_&&s(y,_))return _}return new h(!1)}},78309:(t,e,n)=>{var r=n(44931),o=n(90649),i=n(4224);t.exports=function(t,e,n){var a,u;o(t);try{if(!(a=i(t,"return"))){if("throw"===e)throw n;return n}a=r(a,t)}catch(t){u=!0,a=t}if("throw"===e)throw n;if(u)throw a;return o(a),n}},75700:(t,e,n)=>{"use strict";var r=n(26679).IteratorPrototype,o=n(32814),i=n(52302),a=n(49233),u=n(45347),c=function(){return this};t.exports=function(t,e,n,s){var l=e+" Iterator";return t.prototype=o(r,{next:i(+!s,n)}),a(t,l,!1,!0),u[l]=c,t}},49626:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(59785),a=n(92684),u=n(11055),c=n(75700),s=n(52473),l=n(26213),f=n(49233),p=n(69193),d=n(92446),h=n(39189),y=n(45347),v=n(26679),m=a.PROPER,g=a.CONFIGURABLE,b=v.IteratorPrototype,_=v.BUGGY_SAFARI_ITERATORS,w=h("iterator"),S="keys",C="values",E="entries",I=function(){return this};t.exports=function(t,e,n,a,h,v,O){c(n,e,a);var P,T,A,x=function(t){if(t===h&&N)return N;if(!_&&t in M)return M[t];switch(t){case S:case C:case E:return function(){return new n(this,t)}}return function(){return new n(this)}},k=e+" Iterator",R=!1,M=t.prototype,j=M[w]||M["@@iterator"]||h&&M[h],N=!_&&j||x(h),D="Array"==e&&M.entries||j;if(D&&(P=s(D.call(new t)))!==Object.prototype&&P.next&&(i||s(P)===b||(l?l(P,b):u(P[w])||d(P,w,I)),f(P,k,!0,!0),i&&(y[k]=I)),m&&h==C&&j&&j.name!==C&&(!i&&g?p(M,"name",C):(R=!0,N=function(){return o(j,this)})),h)if(T={values:x(C),keys:v?N:x(S),entries:x(E)},O)for(A in T)(_||R||!(A in M))&&d(M,A,T[A]);else r({target:e,proto:!0,forced:_||R},T);return i&&!O||M[w]===N||d(M,w,N,{name:h}),y[e]=N,T}},26679:(t,e,n)=>{"use strict";var r,o,i,a=n(79061),u=n(11055),c=n(96692),s=n(32814),l=n(52473),f=n(92446),p=n(39189),d=n(59785),h=p("iterator"),y=!1;[].keys&&("next"in(i=[].keys())?(o=l(l(i)))!==Object.prototype&&(r=o):y=!0),!c(r)||a((function(){var t={};return r[h].call(t)!==t}))?r={}:d&&(r=s(r)),u(r[h])||f(r,h,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:y}},45347:t=>{t.exports={}},12244:(t,e,n)=>{var r=n(99536);t.exports=function(t){return r(t.length)}},58245:(t,e,n)=>{var r=n(38982),o=n(79061),i=n(11055),a=n(34863),u=n(4426),c=n(92684).CONFIGURABLE,s=n(27728),l=n(58319),f=l.enforce,p=l.get,d=String,h=Object.defineProperty,y=r("".slice),v=r("".replace),m=r([].join),g=u&&!o((function(){return 8!==h((function(){}),"length",{value:8}).length})),b=String(String).split("String"),_=t.exports=function(t,e,n){"Symbol("===y(d(e),0,7)&&(e="["+v(d(e),/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!a(t,"name")||c&&t.name!==e)&&(u?h(t,"name",{value:e,configurable:!0}):t.name=e),g&&n&&a(n,"arity")&&t.length!==n.arity&&h(t,"length",{value:n.arity});try{n&&a(n,"constructor")&&n.constructor?u&&h(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var r=f(t);return a(r,"source")||(r.source=m(b,"string"==typeof e?e:"")),t};Function.prototype.toString=_((function(){return i(this)&&p(this).source||s(this)}),"toString")},56811:t=>{var e=Math.ceil,n=Math.floor;t.exports=Math.trunc||function(t){var r=+t;return(r>0?n:e)(r)}},26269:(t,e,n)=>{var r,o,i,a,u,c=n(21833),s=n(67302),l=n(77637).f,f=n(21627).set,p=n(72879),d=n(19997),h=n(52134),y=n(89299),v=n(36954),m=c.MutationObserver||c.WebKitMutationObserver,g=c.document,b=c.process,_=c.Promise,w=l(c,"queueMicrotask"),S=w&&w.value;if(!S){var C=new p,E=function(){var t,e;for(v&&(t=b.domain)&&t.exit();e=C.get();)try{e()}catch(t){throw C.head&&r(),t}t&&t.enter()};d||v||y||!m||!g?!h&&_&&_.resolve?((a=_.resolve(void 0)).constructor=_,u=s(a.then,a),r=function(){u(E)}):v?r=function(){b.nextTick(E)}:(f=s(f,c),r=function(){f(E)}):(o=!0,i=g.createTextNode(""),new m(E).observe(i,{characterData:!0}),r=function(){i.data=o=!o}),S=function(t){C.head||r(),C.add(t)}}t.exports=S},76185:(t,e,n)=>{"use strict";var r=n(35476),o=TypeError,i=function(t){var e,n;this.promise=new t((function(t,r){if(void 0!==e||void 0!==n)throw o("Bad Promise constructor");e=t,n=r})),this.resolve=r(e),this.reject=r(n)};t.exports.f=function(t){return new i(t)}},15425:(t,e,n)=>{var r=n(16030),o=TypeError;t.exports=function(t){if(r(t))throw o("The method doesn't accept regular expressions");return t}},55870:(t,e,n)=>{var r=n(21833),o=n(79061),i=n(38982),a=n(96641),u=n(92572).trim,c=n(18986),s=i("".charAt),l=r.parseFloat,f=r.Symbol,p=f&&f.iterator,d=1/l(c+"-0")!=-1/0||p&&!o((function(){l(Object(p))}));t.exports=d?function(t){var e=u(a(t)),n=l(e);return 0===n&&"-"==s(e,0)?-0:n}:l},145:(t,e,n)=>{var r=n(21833),o=n(79061),i=n(38982),a=n(96641),u=n(92572).trim,c=n(18986),s=r.parseInt,l=r.Symbol,f=l&&l.iterator,p=/^[+-]?0x/i,d=i(p.exec),h=8!==s(c+"08")||22!==s(c+"0x16")||f&&!o((function(){s(Object(f))}));t.exports=h?function(t,e){var n=u(a(t));return s(n,e>>>0||(d(p,n)?16:10))}:s},58187:(t,e,n)=>{"use strict";var r=n(4426),o=n(38982),i=n(44931),a=n(79061),u=n(80094),c=n(68255),s=n(46391),l=n(50775),f=n(7461),p=Object.assign,d=Object.defineProperty,h=o([].concat);t.exports=!p||a((function(){if(r&&1!==p({b:1},p(d({},"a",{enumerable:!0,get:function(){d(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),o="abcdefghijklmnopqrst";return t[n]=7,o.split("").forEach((function(t){e[t]=t})),7!=p({},t)[n]||u(p({},e)).join("")!=o}))?function(t,e){for(var n=l(t),o=arguments.length,a=1,p=c.f,d=s.f;o>a;)for(var y,v=f(arguments[a++]),m=p?h(u(v),p(v)):u(v),g=m.length,b=0;g>b;)y=m[b++],r&&!i(d,v,y)||(n[y]=v[y]);return n}:p},32814:(t,e,n)=>{var r,o=n(90649),i=n(2459),a=n(39513),u=n(43343),c=n(75527),s=n(46349),l=n(40693),f="prototype",p="script",d=l("IE_PROTO"),h=function(){},y=function(t){return"<"+p+">"+t+""},v=function(t){t.write(y("")),t.close();var e=t.parentWindow.Object;return t=null,e},m=function(){try{r=new ActiveXObject("htmlfile")}catch(t){}var t,e,n;m="undefined"!=typeof document?document.domain&&r?v(r):(e=s("iframe"),n="java"+p+":",e.style.display="none",c.appendChild(e),e.src=String(n),(t=e.contentWindow.document).open(),t.write(y("document.F=Object")),t.close(),t.F):v(r);for(var o=a.length;o--;)delete m[f][a[o]];return m()};u[d]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(h[f]=o(t),n=new h,h[f]=null,n[d]=t):n=m(),void 0===e?n:i.f(n,e)}},2459:(t,e,n)=>{var r=n(4426),o=n(75828),i=n(59143),a=n(90649),u=n(4395),c=n(80094);e.f=r&&!o?Object.defineProperties:function(t,e){a(t);for(var n,r=u(e),o=c(e),s=o.length,l=0;s>l;)i.f(t,n=o[l++],r[n]);return t}},59143:(t,e,n)=>{var r=n(4426),o=n(99667),i=n(75828),a=n(90649),u=n(50243),c=TypeError,s=Object.defineProperty,l=Object.getOwnPropertyDescriptor,f="enumerable",p="configurable",d="writable";e.f=r?i?function(t,e,n){if(a(t),e=u(e),a(n),"function"==typeof t&&"prototype"===e&&"value"in n&&d in n&&!n[d]){var r=l(t,e);r&&r[d]&&(t[e]=n.value,n={configurable:p in n?n[p]:r[p],enumerable:f in n?n[f]:r[f],writable:!1})}return s(t,e,n)}:s:function(t,e,n){if(a(t),e=u(e),a(n),o)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw c("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},77637:(t,e,n)=>{var r=n(4426),o=n(44931),i=n(46391),a=n(52302),u=n(4395),c=n(50243),s=n(34863),l=n(99667),f=Object.getOwnPropertyDescriptor;e.f=r?f:function(t,e){if(t=u(t),e=c(e),l)try{return f(t,e)}catch(t){}if(s(t,e))return a(!o(i.f,t,e),t[e])}},83744:(t,e,n)=>{var r=n(17170),o=n(4395),i=n(47210).f,a=n(10301),u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"Window"==r(t)?function(t){try{return i(t)}catch(t){return a(u)}}(t):i(o(t))}},47210:(t,e,n)=>{var r=n(4114),o=n(39513).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,o)}},68255:(t,e)=>{e.f=Object.getOwnPropertySymbols},52473:(t,e,n)=>{var r=n(34863),o=n(11055),i=n(50775),a=n(40693),u=n(16797),c=a("IE_PROTO"),s=Object,l=s.prototype;t.exports=u?s.getPrototypeOf:function(t){var e=i(t);if(r(e,c))return e[c];var n=e.constructor;return o(n)&&e instanceof n?n.prototype:e instanceof s?l:null}},81278:(t,e,n)=>{var r=n(79061),o=n(96692),i=n(17170),a=n(65642),u=Object.isExtensible,c=r((function(){u(1)}));t.exports=c||a?function(t){return!!o(t)&&(!a||"ArrayBuffer"!=i(t))&&(!u||u(t))}:u},47931:(t,e,n)=>{var r=n(38982);t.exports=r({}.isPrototypeOf)},4114:(t,e,n)=>{var r=n(38982),o=n(34863),i=n(4395),a=n(20895).indexOf,u=n(43343),c=r([].push);t.exports=function(t,e){var n,r=i(t),s=0,l=[];for(n in r)!o(u,n)&&o(r,n)&&c(l,n);for(;e.length>s;)o(r,n=e[s++])&&(~a(l,n)||c(l,n));return l}},80094:(t,e,n)=>{var r=n(4114),o=n(39513);t.exports=Object.keys||function(t){return r(t,o)}},46391:(t,e)=>{"use strict";var n={}.propertyIsEnumerable,r=Object.getOwnPropertyDescriptor,o=r&&!n.call({1:2},1);e.f=o?function(t){var e=r(this,t);return!!e&&e.enumerable}:n},26213:(t,e,n)=>{var r=n(67652),o=n(90649),i=n(1520);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,n={};try{(t=r(Object.prototype,"__proto__","set"))(n,[]),e=n instanceof Array}catch(t){}return function(n,r){return o(n),i(r),e?t(n,r):n.__proto__=r,n}}():void 0)},70671:(t,e,n)=>{var r=n(4426),o=n(79061),i=n(38982),a=n(52473),u=n(80094),c=n(4395),s=i(n(46391).f),l=i([].push),f=r&&o((function(){var t=Object.create(null);return t[2]=2,!s(t,2)})),p=function(t){return function(e){for(var n,o=c(e),i=u(o),p=f&&null===a(o),d=i.length,h=0,y=[];d>h;)n=i[h++],r&&!(p?n in o:s(o,n))||l(y,t?[n,o[n]]:o[n]);return y}};t.exports={entries:p(!0),values:p(!1)}},42553:(t,e,n)=>{"use strict";var r=n(13878),o=n(75493);t.exports=r?{}.toString:function(){return"[object "+o(this)+"]"}},2272:(t,e,n)=>{var r=n(44931),o=n(11055),i=n(96692),a=TypeError;t.exports=function(t,e){var n,u;if("string"===e&&o(n=t.toString)&&!i(u=r(n,t)))return u;if(o(n=t.valueOf)&&!i(u=r(n,t)))return u;if("string"!==e&&o(n=t.toString)&&!i(u=r(n,t)))return u;throw a("Can't convert object to primitive value")}},8517:(t,e,n)=>{var r=n(78797),o=n(38982),i=n(47210),a=n(68255),u=n(90649),c=o([].concat);t.exports=r("Reflect","ownKeys")||function(t){var e=i.f(u(t)),n=a.f;return n?c(e,n(t)):e}},16665:(t,e,n)=>{var r=n(21833);t.exports=r},63341:t=>{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},43322:(t,e,n)=>{var r=n(21833),o=n(70828),i=n(11055),a=n(96942),u=n(27728),c=n(39189),s=n(43704),l=n(99574),f=n(59785),p=n(36918),d=o&&o.prototype,h=c("species"),y=!1,v=i(r.PromiseRejectionEvent),m=a("Promise",(function(){var t=u(o),e=t!==String(o);if(!e&&66===p)return!0;if(f&&(!d.catch||!d.finally))return!0;if(!p||p<51||!/native code/.test(t)){var n=new o((function(t){t(1)})),r=function(t){t((function(){}),(function(){}))};if((n.constructor={})[h]=r,!(y=n.then((function(){}))instanceof r))return!0}return!e&&(s||l)&&!v}));t.exports={CONSTRUCTOR:m,REJECTION_EVENT:v,SUBCLASSING:y}},70828:(t,e,n)=>{var r=n(21833);t.exports=r.Promise},77472:(t,e,n)=>{var r=n(90649),o=n(96692),i=n(76185);t.exports=function(t,e){if(r(t),o(e)&&e.constructor===t)return e;var n=i.f(t);return(0,n.resolve)(e),n.promise}},32291:(t,e,n)=>{var r=n(70828),o=n(25542),i=n(43322).CONSTRUCTOR;t.exports=i||!o((function(t){r.all(t).then(void 0,(function(){}))}))},76434:(t,e,n)=>{var r=n(59143).f;t.exports=function(t,e,n){n in t||r(t,n,{configurable:!0,get:function(){return e[n]},set:function(t){e[n]=t}})}},72879:t=>{var e=function(){this.head=null,this.tail=null};e.prototype={add:function(t){var e={item:t,next:null},n=this.tail;n?n.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return null===(this.head=t.next)&&(this.tail=null),t.item}},t.exports=e},47160:(t,e,n)=>{var r=n(44931),o=n(90649),i=n(11055),a=n(17170),u=n(74989),c=TypeError;t.exports=function(t,e){var n=t.exec;if(i(n)){var s=r(n,t,e);return null!==s&&o(s),s}if("RegExp"===a(t))return r(u,t,e);throw c("RegExp#exec called on incompatible receiver")}},74989:(t,e,n)=>{"use strict";var r,o,i=n(44931),a=n(38982),u=n(96641),c=n(1881),s=n(60303),l=n(51435),f=n(32814),p=n(58319).get,d=n(99121),h=n(90324),y=l("native-string-replace",String.prototype.replace),v=RegExp.prototype.exec,m=v,g=a("".charAt),b=a("".indexOf),_=a("".replace),w=a("".slice),S=(o=/b*/g,i(v,r=/a/,"a"),i(v,o,"a"),0!==r.lastIndex||0!==o.lastIndex),C=s.BROKEN_CARET,E=void 0!==/()??/.exec("")[1];(S||E||C||d||h)&&(m=function(t){var e,n,r,o,a,s,l,d=this,h=p(d),I=u(t),O=h.raw;if(O)return O.lastIndex=d.lastIndex,e=i(m,O,I),d.lastIndex=O.lastIndex,e;var P=h.groups,T=C&&d.sticky,A=i(c,d),x=d.source,k=0,R=I;if(T&&(A=_(A,"y",""),-1===b(A,"g")&&(A+="g"),R=w(I,d.lastIndex),d.lastIndex>0&&(!d.multiline||d.multiline&&"\n"!==g(I,d.lastIndex-1))&&(x="(?: "+x+")",R=" "+R,k++),n=new RegExp("^(?:"+x+")",A)),E&&(n=new RegExp("^"+x+"$(?!\\s)",A)),S&&(r=d.lastIndex),o=i(v,T?n:d,R),T?o?(o.input=w(o.input,k),o[0]=w(o[0],k),o.index=d.lastIndex,d.lastIndex+=o[0].length):d.lastIndex=0:S&&o&&(d.lastIndex=d.global?o.index+o[0].length:r),E&&o&&o.length>1&&i(y,o[0],n,(function(){for(a=1;a{"use strict";var r=n(90649);t.exports=function(){var t=r(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},84228:(t,e,n)=>{var r=n(44931),o=n(34863),i=n(47931),a=n(1881),u=RegExp.prototype;t.exports=function(t){var e=t.flags;return void 0!==e||"flags"in u||o(t,"flags")||!i(u,t)?e:r(a,t)}},60303:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp,i=r((function(){var t=o("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),a=i||r((function(){return!o("a","y").sticky})),u=i||r((function(){var t=o("^r","gy");return t.lastIndex=2,null!=t.exec("str")}));t.exports={BROKEN_CARET:u,MISSED_STICKY:a,UNSUPPORTED_Y:i}},99121:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp;t.exports=r((function(){var t=o(".","s");return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)}))},90324:(t,e,n)=>{var r=n(79061),o=n(21833).RegExp;t.exports=r((function(){var t=o("(?b)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$c")}))},29412:(t,e,n)=>{var r=n(40899),o=TypeError;t.exports=function(t){if(r(t))throw o("Can't call method on "+t);return t}},45448:t=>{t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},18807:(t,e,n)=>{"use strict";var r=n(78797),o=n(61548),i=n(39189),a=n(4426),u=i("species");t.exports=function(t){var e=r(t);a&&e&&!e[u]&&o(e,u,{configurable:!0,get:function(){return this}})}},49233:(t,e,n)=>{var r=n(59143).f,o=n(34863),i=n(39189)("toStringTag");t.exports=function(t,e,n){t&&!n&&(t=t.prototype),t&&!o(t,i)&&r(t,i,{configurable:!0,value:e})}},40693:(t,e,n)=>{var r=n(51435),o=n(64550),i=r("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},47099:(t,e,n)=>{var r=n(21833),o=n(11891),i="__core-js_shared__",a=r[i]||o(i,{});t.exports=a},51435:(t,e,n)=>{var r=n(59785),o=n(47099);(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.31.0",mode:r?"pure":"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})},46439:(t,e,n)=>{var r=n(90649),o=n(68634),i=n(40899),a=n(39189)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||i(n=r(u)[a])?e:o(n)}},15927:(t,e,n)=>{var r=n(79061);t.exports=function(t){return r((function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}))}},65877:(t,e,n)=>{var r=n(38982),o=n(91129),i=n(96641),a=n(29412),u=r("".charAt),c=r("".charCodeAt),s=r("".slice),l=function(t){return function(e,n){var r,l,f=i(a(e)),p=o(n),d=f.length;return p<0||p>=d?t?"":void 0:(r=c(f,p))<55296||r>56319||p+1===d||(l=c(f,p+1))<56320||l>57343?t?u(f,p):r:t?s(f,p,p+2):l-56320+(r-55296<<10)+65536}};t.exports={codeAt:l(!1),charAt:l(!0)}},96929:(t,e,n)=>{var r=n(60514);t.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(r)},8439:(t,e,n)=>{var r=n(38982),o=n(99536),i=n(96641),a=n(20471),u=n(29412),c=r(a),s=r("".slice),l=Math.ceil,f=function(t){return function(e,n,r){var a,f,p=i(u(e)),d=o(n),h=p.length,y=void 0===r?" ":i(r);return d<=h||""==y?p:((f=c(y,l((a=d-h)/y.length))).length>a&&(f=s(f,0,a)),t?p+f:f+p)}};t.exports={start:f(!1),end:f(!0)}},20471:(t,e,n)=>{"use strict";var r=n(91129),o=n(96641),i=n(29412),a=RangeError;t.exports=function(t){var e=o(i(this)),n="",u=r(t);if(u<0||u==1/0)throw a("Wrong number of repetitions");for(;u>0;(u>>>=1)&&(e+=e))1&u&&(n+=e);return n}},92024:(t,e,n)=>{"use strict";var r=n(92572).end,o=n(4160);t.exports=o("trimEnd")?function(){return r(this)}:"".trimEnd},4160:(t,e,n)=>{var r=n(92684).PROPER,o=n(79061),i=n(18986);t.exports=function(t){return o((function(){return!!i[t]()||"​…᠎"!=="​…᠎"[t]()||r&&i[t].name!==t}))}},10409:(t,e,n)=>{"use strict";var r=n(92572).start,o=n(4160);t.exports=o("trimStart")?function(){return r(this)}:"".trimStart},92572:(t,e,n)=>{var r=n(38982),o=n(29412),i=n(96641),a=n(18986),u=r("".replace),c=RegExp("^["+a+"]+"),s=RegExp("(^|[^"+a+"])["+a+"]+$"),l=function(t){return function(e){var n=i(o(e));return 1&t&&(n=u(n,c,"")),2&t&&(n=u(n,s,"$1")),n}};t.exports={start:l(1),end:l(2),trim:l(3)}},12289:(t,e,n)=>{var r=n(36918),o=n(79061),i=n(21833).String;t.exports=!!Object.getOwnPropertySymbols&&!o((function(){var t=Symbol();return!i(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&r&&r<41}))},80236:(t,e,n)=>{var r=n(44931),o=n(78797),i=n(39189),a=n(92446);t.exports=function(){var t=o("Symbol"),e=t&&t.prototype,n=e&&e.valueOf,u=i("toPrimitive");e&&!e[u]&&a(e,u,(function(t){return r(n,this)}),{arity:1})}},5462:(t,e,n)=>{var r=n(12289);t.exports=r&&!!Symbol.for&&!!Symbol.keyFor},21627:(t,e,n)=>{var r,o,i,a,u=n(21833),c=n(33247),s=n(67302),l=n(11055),f=n(34863),p=n(79061),d=n(75527),h=n(72582),y=n(46349),v=n(89614),m=n(19997),g=n(36954),b=u.setImmediate,_=u.clearImmediate,w=u.process,S=u.Dispatch,C=u.Function,E=u.MessageChannel,I=u.String,O=0,P={},T="onreadystatechange";p((function(){r=u.location}));var A=function(t){if(f(P,t)){var e=P[t];delete P[t],e()}},x=function(t){return function(){A(t)}},k=function(t){A(t.data)},R=function(t){u.postMessage(I(t),r.protocol+"//"+r.host)};b&&_||(b=function(t){v(arguments.length,1);var e=l(t)?t:C(t),n=h(arguments,1);return P[++O]=function(){c(e,void 0,n)},o(O),O},_=function(t){delete P[t]},g?o=function(t){w.nextTick(x(t))}:S&&S.now?o=function(t){S.now(x(t))}:E&&!m?(a=(i=new E).port2,i.port1.onmessage=k,o=s(a.postMessage,a)):u.addEventListener&&l(u.postMessage)&&!u.importScripts&&r&&"file:"!==r.protocol&&!p(R)?(o=R,u.addEventListener("message",k,!1)):o=T in y("script")?function(t){d.appendChild(y("script"))[T]=function(){d.removeChild(this),A(t)}}:function(t){setTimeout(x(t),0)}),t.exports={set:b,clear:_}},57746:(t,e,n)=>{var r=n(38982);t.exports=r(1..valueOf)},79036:(t,e,n)=>{var r=n(91129),o=Math.max,i=Math.min;t.exports=function(t,e){var n=r(t);return n<0?o(n+e,0):i(n,e)}},2042:(t,e,n)=>{var r=n(91129),o=n(99536),i=RangeError;t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=o(e);if(e!==n)throw i("Wrong length or index");return n}},4395:(t,e,n)=>{var r=n(7461),o=n(29412);t.exports=function(t){return r(o(t))}},91129:(t,e,n)=>{var r=n(56811);t.exports=function(t){var e=+t;return e!=e||0===e?0:r(e)}},99536:(t,e,n)=>{var r=n(91129),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},50775:(t,e,n)=>{var r=n(29412),o=Object;t.exports=function(t){return o(r(t))}},33983:(t,e,n)=>{var r=n(44931),o=n(96692),i=n(30907),a=n(4224),u=n(2272),c=n(39189),s=TypeError,l=c("toPrimitive");t.exports=function(t,e){if(!o(t)||i(t))return t;var n,c=a(t,l);if(c){if(void 0===e&&(e="default"),n=r(c,t,e),!o(n)||i(n))return n;throw s("Can't convert object to primitive value")}return void 0===e&&(e="number"),u(t,e)}},50243:(t,e,n)=>{var r=n(33983),o=n(30907);t.exports=function(t){var e=r(t,"string");return o(e)?e:e+""}},13878:(t,e,n)=>{var r={};r[n(39189)("toStringTag")]="z",t.exports="[object z]"===String(r)},96641:(t,e,n)=>{var r=n(75493),o=String;t.exports=function(t){if("Symbol"===r(t))throw TypeError("Cannot convert a Symbol value to a string");return o(t)}},79269:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},64550:(t,e,n)=>{var r=n(38982),o=0,i=Math.random(),a=r(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++o+i,36)}},92010:(t,e,n)=>{var r=n(12289);t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},75828:(t,e,n)=>{var r=n(4426),o=n(79061);t.exports=r&&o((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},89614:t=>{var e=TypeError;t.exports=function(t,n){if(t{var r=n(21833),o=n(11055),i=r.WeakMap;t.exports=o(i)&&/native code/.test(String(i))},1749:(t,e,n)=>{var r=n(16665),o=n(34863),i=n(2561),a=n(59143).f;t.exports=function(t){var e=r.Symbol||(r.Symbol={});o(e,t)||a(e,t,{value:i.f(t)})}},2561:(t,e,n)=>{var r=n(39189);e.f=r},39189:(t,e,n)=>{var r=n(21833),o=n(51435),i=n(34863),a=n(64550),u=n(12289),c=n(92010),s=r.Symbol,l=o("wks"),f=c?s.for||s:s&&s.withoutSetter||a;t.exports=function(t){return i(l,t)||(l[t]=u&&i(s,t)?s[t]:f("Symbol."+t)),l[t]}},18986:t=>{t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},33217:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(70668),a=n(18807),u="ArrayBuffer",c=i[u];r({global:!0,constructor:!0,forced:o[u]!==c},{ArrayBuffer:c}),a(u)},79851:(t,e,n)=>{"use strict";var r=n(58288),o=n(46526),i=n(79061),a=n(70668),u=n(90649),c=n(79036),s=n(99536),l=n(46439),f=a.ArrayBuffer,p=a.DataView,d=p.prototype,h=o(f.prototype.slice),y=o(d.getUint8),v=o(d.setUint8);r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:i((function(){return!new f(2).slice(1,void 0).byteLength}))},{slice:function(t,e){if(h&&void 0===e)return h(u(this),t);for(var n=u(this).byteLength,r=c(t,n),o=c(void 0===e?n:e,n),i=new(l(this,f))(s(o-r)),a=new p(this),d=new p(i),m=0;r{"use strict";var r=n(58288),o=n(79061),i=n(57886),a=n(96692),u=n(50775),c=n(12244),s=n(68655),l=n(25762),f=n(88627),p=n(20423),d=n(39189),h=n(36918),y=d("isConcatSpreadable"),v=h>=51||!o((function(){var t=[];return t[y]=!1,t.concat()[0]!==t})),m=function(t){if(!a(t))return!1;var e=t[y];return void 0!==e?!!e:i(t)};r({target:"Array",proto:!0,arity:1,forced:!v||!p("concat")},{concat:function(t){var e,n,r,o,i,a=u(this),p=f(a,0),d=0;for(e=-1,r=arguments.length;e{var r=n(58288),o=n(70419),i=n(44595);r({target:"Array",proto:!0},{fill:o}),i("fill")},14266:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).filter;r({target:"Array",proto:!0,forced:!n(20423)("filter")},{filter:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},11466:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).findIndex,i=n(44595),a="findIndex",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{findIndex:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i(a)},10715:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).find,i=n(44595),a="find",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{find:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i(a)},508:(t,e,n)=>{"use strict";var r=n(58288),o=n(96493),i=n(35476),a=n(50775),u=n(12244),c=n(88627);r({target:"Array",proto:!0},{flatMap:function(t){var e,n=a(this),r=u(n);return i(t),(e=c(n,0)).length=o(e,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),e}})},2184:(t,e,n)=>{var r=n(58288),o=n(36658);r({target:"Array",stat:!0,forced:!n(25542)((function(t){Array.from(t)}))},{from:o})},88477:(t,e,n)=>{"use strict";var r=n(58288),o=n(20895).includes,i=n(79061),a=n(44595);r({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),a("includes")},47818:(t,e,n)=>{"use strict";var r=n(58288),o=n(46526),i=n(20895).indexOf,a=n(46644),u=o([].indexOf),c=!!u&&1/u([1],1,-0)<0;r({target:"Array",proto:!0,forced:c||!a("indexOf")},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return c?u(this,t,e)||0:i(this,t,e)}})},14718:(t,e,n)=>{"use strict";var r=n(4395),o=n(44595),i=n(45347),a=n(58319),u=n(59143).f,c=n(49626),s=n(42579),l=n(59785),f=n(4426),p="Array Iterator",d=a.set,h=a.getterFor(p);t.exports=c(Array,"Array",(function(t,e){d(this,{type:p,target:r(t),index:0,kind:e})}),(function(){var t=h(this),e=t.target,n=t.kind,r=t.index++;return!e||r>=e.length?(t.target=void 0,s(void 0,!0)):s("keys"==n?r:"values"==n?e[r]:[r,e[r]],!1)}),"values");var y=i.Arguments=i.Array;if(o("keys"),o("values"),o("entries"),!l&&f&&"values"!==y.name)try{u(y,"name",{value:"values"})}catch(t){}},57188:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(7461),a=n(4395),u=n(46644),c=o([].join);r({target:"Array",proto:!0,forced:i!=Object||!u("join",",")},{join:function(t){return c(a(this),void 0===t?",":t)}})},35823:(t,e,n)=>{var r=n(58288),o=n(37041);r({target:"Array",proto:!0,forced:o!==[].lastIndexOf},{lastIndexOf:o})},80404:(t,e,n)=>{"use strict";var r=n(58288),o=n(31567).map;r({target:"Array",proto:!0,forced:!n(20423)("map")},{map:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},5360:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(57886),a=o([].reverse),u=[1,2];r({target:"Array",proto:!0,forced:String(u)===String(u.reverse())},{reverse:function(){return i(this)&&(this.length=this.length),a(this)}})},44396:(t,e,n)=>{"use strict";var r=n(58288),o=n(57886),i=n(11547),a=n(96692),u=n(79036),c=n(12244),s=n(4395),l=n(25762),f=n(39189),p=n(20423),d=n(72582),h=p("slice"),y=f("species"),v=Array,m=Math.max;r({target:"Array",proto:!0,forced:!h},{slice:function(t,e){var n,r,f,p=s(this),h=c(p),g=u(t,h),b=u(void 0===e?h:e,h);if(o(p)&&(n=p.constructor,(i(n)&&(n===v||o(n.prototype))||a(n)&&null===(n=n[y]))&&(n=void 0),n===v||void 0===n))return d(p,g,b);for(r=new(void 0===n?v:n)(m(b-g,0)),f=0;g{"use strict";var r=n(58288),o=n(38982),i=n(35476),a=n(50775),u=n(12244),c=n(87472),s=n(96641),l=n(79061),f=n(84326),p=n(46644),d=n(27496),h=n(36928),y=n(36918),v=n(53522),m=[],g=o(m.sort),b=o(m.push),_=l((function(){m.sort(void 0)})),w=l((function(){m.sort(null)})),S=p("sort"),C=!l((function(){if(y)return y<70;if(!(d&&d>3)){if(h)return!0;if(v)return v<603;var t,e,n,r,o="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)m.push({k:e+r,v:n})}for(m.sort((function(t,e){return e.v-t.v})),r=0;rs(n)?1:-1}}(t)),n=u(o),r=0;r{"use strict";var r=n(58288),o=n(50775),i=n(79036),a=n(91129),u=n(12244),c=n(41909),s=n(68655),l=n(88627),f=n(25762),p=n(87472),d=n(20423)("splice"),h=Math.max,y=Math.min;r({target:"Array",proto:!0,forced:!d},{splice:function(t,e){var n,r,d,v,m,g,b=o(this),_=u(b),w=i(t,_),S=arguments.length;for(0===S?n=r=0:1===S?(n=0,r=_-w):(n=S-2,r=y(h(a(e),0),_-w)),s(_+n-r),d=l(b,r),v=0;v_-r+n;v--)p(b,v-1)}else if(n>r)for(v=_-r;v>w;v--)g=v+n-1,(m=v+r-1)in b?b[g]=b[m]:p(b,g);for(v=0;v{n(44595)("flatMap")},62342:(t,e,n)=>{var r=n(34863),o=n(92446),i=n(55362),a=n(39189)("toPrimitive"),u=Date.prototype;r(u,a)||o(u,a,i)},18864:(t,e,n)=>{var r=n(4426),o=n(92684).EXISTS,i=n(38982),a=n(61548),u=Function.prototype,c=i(u.toString),s=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,l=i(s.exec);r&&!o&&a(u,"name",{configurable:!0,get:function(){try{return l(s,c(this))[1]}catch(t){return""}}})},81172:(t,e,n)=>{var r=n(58288),o=n(78797),i=n(33247),a=n(44931),u=n(38982),c=n(79061),s=n(11055),l=n(30907),f=n(72582),p=n(54875),d=n(12289),h=String,y=o("JSON","stringify"),v=u(/./.exec),m=u("".charAt),g=u("".charCodeAt),b=u("".replace),_=u(1..toString),w=/[\uD800-\uDFFF]/g,S=/^[\uD800-\uDBFF]$/,C=/^[\uDC00-\uDFFF]$/,E=!d||c((function(){var t=o("Symbol")();return"[null]"!=y([t])||"{}"!=y({a:t})||"{}"!=y(Object(t))})),I=c((function(){return'"\\udf06\\ud834"'!==y("\udf06\ud834")||'"\\udead"'!==y("\udead")})),O=function(t,e){var n=f(arguments),r=p(e);if(s(r)||void 0!==t&&!l(t))return n[1]=function(t,e){if(s(r)&&(e=a(r,this,h(t),e)),!l(e))return e},i(y,null,n)},P=function(t,e,n){var r=m(n,e-1),o=m(n,e+1);return v(S,t)&&!v(C,o)||v(C,t)&&!v(S,r)?"\\u"+_(g(t,0),16):t};y&&r({target:"JSON",stat:!0,arity:3,forced:E||I},{stringify:function(t,e,n){var r=f(arguments),o=i(E?O:y,null,r);return I&&"string"==typeof o?b(o,w,P):o}})},54513:(t,e,n)=>{"use strict";n(35365)("Map",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(49720))},20363:(t,e,n)=>{n(54513)},25226:(t,e,n)=>{"use strict";var r=n(58288),o=n(59785),i=n(4426),a=n(21833),u=n(16665),c=n(38982),s=n(96942),l=n(34863),f=n(86953),p=n(47931),d=n(30907),h=n(33983),y=n(79061),v=n(47210).f,m=n(77637).f,g=n(59143).f,b=n(57746),_=n(92572).trim,w="Number",S=a[w],C=u[w],E=S.prototype,I=a.TypeError,O=c("".slice),P=c("".charCodeAt),T=s(w,!S(" 0o1")||!S("0b1")||S("+0x1")),A=function(t){var e,n=arguments.length<1?0:S(function(t){var e=h(t,"number");return"bigint"==typeof e?e:function(t){var e,n,r,o,i,a,u,c,s=h(t,"number");if(d(s))throw I("Cannot convert a Symbol value to a number");if("string"==typeof s&&s.length>2)if(s=_(s),43===(e=P(s,0))||45===e){if(88===(n=P(s,2))||120===n)return NaN}else if(48===e){switch(P(s,1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+s}for(a=(i=O(s,2)).length,u=0;uo)return NaN;return parseInt(i,r)}return+s}(e)}(t));return p(E,e=this)&&y((function(){b(e)}))?f(Object(n),this,A):n};A.prototype=E,T&&!o&&(E.constructor=A),r({global:!0,constructor:!0,wrap:!0,forced:T},{Number:A});var x=function(t,e){for(var n,r=i?v(e):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),o=0;r.length>o;o++)l(e,n=r[o])&&!l(t,n)&&g(t,n,m(e,n))};o&&C&&x(u[w],C),(T||o)&&x(u[w],S)},69204:(t,e,n)=>{n(58288)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},90291:(t,e,n)=>{var r=n(58288),o=n(58187);r({target:"Object",stat:!0,arity:2,forced:Object.assign!==o},{assign:o})},976:(t,e,n)=>{var r=n(58288),o=n(70671).entries;r({target:"Object",stat:!0},{entries:function(t){return o(t)}})},56949:(t,e,n)=>{var r=n(58288),o=n(1566),i=n(79061),a=n(96692),u=n(89277).onFreeze,c=Object.freeze;r({target:"Object",stat:!0,forced:i((function(){c(1)})),sham:!o},{freeze:function(t){return c&&a(t)?c(u(t)):t}})},15277:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(4395),a=n(77637).f,u=n(4426);r({target:"Object",stat:!0,forced:!u||o((function(){a(1)})),sham:!u},{getOwnPropertyDescriptor:function(t,e){return a(i(t),e)}})},32194:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(83744).f;r({target:"Object",stat:!0,forced:o((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:i})},69047:(t,e,n)=>{var r=n(58288),o=n(12289),i=n(79061),a=n(68255),u=n(50775);r({target:"Object",stat:!0,forced:!o||i((function(){a.f(1)}))},{getOwnPropertySymbols:function(t){var e=a.f;return e?e(u(t)):[]}})},46977:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(50775),a=n(52473),u=n(16797);r({target:"Object",stat:!0,forced:o((function(){a(1)})),sham:!u},{getPrototypeOf:function(t){return a(i(t))}})},38085:(t,e,n)=>{var r=n(58288),o=n(79061),i=n(96692),a=n(17170),u=n(65642),c=Object.isFrozen;r({target:"Object",stat:!0,forced:u||o((function(){c(1)}))},{isFrozen:function(t){return!i(t)||!(!u||"ArrayBuffer"!=a(t))||!!c&&c(t)}})},21894:(t,e,n)=>{var r=n(58288),o=n(50775),i=n(80094);r({target:"Object",stat:!0,forced:n(79061)((function(){i(1)}))},{keys:function(t){return i(o(t))}})},68461:(t,e,n)=>{n(58288)({target:"Object",stat:!0},{setPrototypeOf:n(26213)})},13521:(t,e,n)=>{var r=n(13878),o=n(92446),i=n(42553);r||o(Object.prototype,"toString",i,{unsafe:!0})},8933:(t,e,n)=>{var r=n(58288),o=n(55870);r({global:!0,forced:parseFloat!=o},{parseFloat:o})},17186:(t,e,n)=>{var r=n(58288),o=n(145);r({global:!0,forced:parseInt!=o},{parseInt:o})},47333:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(35476),a=n(76185),u=n(63341),c=n(4846);r({target:"Promise",stat:!0,forced:n(32291)},{all:function(t){var e=this,n=a.f(e),r=n.resolve,s=n.reject,l=u((function(){var n=i(e.resolve),a=[],u=0,l=1;c(t,(function(t){var i=u++,c=!1;l++,o(n,e,t).then((function(t){c||(c=!0,a[i]=t,--l||r(a))}),s)})),--l||r(a)}));return l.error&&s(l.value),n.promise}})},8269:(t,e,n)=>{"use strict";var r=n(58288),o=n(59785),i=n(43322).CONSTRUCTOR,a=n(70828),u=n(78797),c=n(11055),s=n(92446),l=a&&a.prototype;if(r({target:"Promise",proto:!0,forced:i,real:!0},{catch:function(t){return this.then(void 0,t)}}),!o&&c(a)){var f=u("Promise").prototype.catch;l.catch!==f&&s(l,"catch",f,{unsafe:!0})}},37214:(t,e,n)=>{"use strict";var r,o,i,a=n(58288),u=n(59785),c=n(36954),s=n(21833),l=n(44931),f=n(92446),p=n(26213),d=n(49233),h=n(18807),y=n(35476),v=n(11055),m=n(96692),g=n(37809),b=n(46439),_=n(21627).set,w=n(26269),S=n(69991),C=n(63341),E=n(72879),I=n(58319),O=n(70828),P=n(43322),T=n(76185),A="Promise",x=P.CONSTRUCTOR,k=P.REJECTION_EVENT,R=P.SUBCLASSING,M=I.getterFor(A),j=I.set,N=O&&O.prototype,D=O,L=N,z=s.TypeError,U=s.document,F=s.process,B=T.f,q=B,V=!!(U&&U.createEvent&&s.dispatchEvent),G="unhandledrejection",H=function(t){var e;return!(!m(t)||!v(e=t.then))&&e},Y=function(t,e){var n,r,o,i=e.value,a=1==e.state,u=a?t.ok:t.fail,c=t.resolve,s=t.reject,f=t.domain;try{u?(a||(2===e.rejection&&Z(e),e.rejection=1),!0===u?n=i:(f&&f.enter(),n=u(i),f&&(f.exit(),o=!0)),n===t.promise?s(z("Promise-chain cycle")):(r=H(n))?l(r,n,c,s):c(n)):s(i)}catch(t){f&&!o&&f.exit(),s(t)}},W=function(t,e){t.notified||(t.notified=!0,w((function(){for(var n,r=t.reactions;n=r.get();)Y(n,t);t.notified=!1,e&&!t.rejection&&$(t)})))},K=function(t,e,n){var r,o;V?((r=U.createEvent("Event")).promise=e,r.reason=n,r.initEvent(t,!1,!0),s.dispatchEvent(r)):r={promise:e,reason:n},!k&&(o=s["on"+t])?o(r):t===G&&S("Unhandled promise rejection",n)},$=function(t){l(_,s,(function(){var e,n=t.facade,r=t.value;if(Q(t)&&(e=C((function(){c?F.emit("unhandledRejection",r,n):K(G,n,r)})),t.rejection=c||Q(t)?2:1,e.error))throw e.value}))},Q=function(t){return 1!==t.rejection&&!t.parent},Z=function(t){l(_,s,(function(){var e=t.facade;c?F.emit("rejectionHandled",e):K("rejectionhandled",e,t.value)}))},J=function(t,e,n){return function(r){t(e,r,n)}},X=function(t,e,n){t.done||(t.done=!0,n&&(t=n),t.value=e,t.state=2,W(t,!0))},tt=function(t,e,n){if(!t.done){t.done=!0,n&&(t=n);try{if(t.facade===e)throw z("Promise can't be resolved itself");var r=H(e);r?w((function(){var n={done:!1};try{l(r,e,J(tt,n,t),J(X,n,t))}catch(e){X(n,e,t)}})):(t.value=e,t.state=1,W(t,!1))}catch(e){X({done:!1},e,t)}}};if(x&&(L=(D=function(t){g(this,L),y(t),l(r,this);var e=M(this);try{t(J(tt,e),J(X,e))}catch(t){X(e,t)}}).prototype,(r=function(t){j(this,{type:A,done:!1,notified:!1,parent:!1,reactions:new E,rejection:!1,state:0,value:void 0})}).prototype=f(L,"then",(function(t,e){var n=M(this),r=B(b(this,D));return n.parent=!0,r.ok=!v(t)||t,r.fail=v(e)&&e,r.domain=c?F.domain:void 0,0==n.state?n.reactions.add(r):w((function(){Y(r,n)})),r.promise})),o=function(){var t=new r,e=M(t);this.promise=t,this.resolve=J(tt,e),this.reject=J(X,e)},T.f=B=function(t){return t===D||void 0===t?new o(t):q(t)},!u&&v(O)&&N!==Object.prototype)){i=N.then,R||f(N,"then",(function(t,e){var n=this;return new D((function(t,e){l(i,n,t,e)})).then(t,e)}),{unsafe:!0});try{delete N.constructor}catch(t){}p&&p(N,L)}a({global:!0,constructor:!0,wrap:!0,forced:x},{Promise:D}),d(D,A,!1,!0),h(A)},67536:(t,e,n)=>{n(37214),n(47333),n(8269),n(7757),n(16811),n(73938)},7757:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(35476),a=n(76185),u=n(63341),c=n(4846);r({target:"Promise",stat:!0,forced:n(32291)},{race:function(t){var e=this,n=a.f(e),r=n.reject,s=u((function(){var a=i(e.resolve);c(t,(function(t){o(a,e,t).then(n.resolve,r)}))}));return s.error&&r(s.value),n.promise}})},16811:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931),i=n(76185);r({target:"Promise",stat:!0,forced:n(43322).CONSTRUCTOR},{reject:function(t){var e=i.f(this);return o(e.reject,void 0,t),e.promise}})},73938:(t,e,n)=>{"use strict";var r=n(58288),o=n(78797),i=n(59785),a=n(70828),u=n(43322).CONSTRUCTOR,c=n(77472),s=o("Promise"),l=i&&!u;r({target:"Promise",stat:!0,forced:i||u},{resolve:function(t){return c(l&&this===s?a:this,t)}})},84090:(t,e,n)=>{var r=n(4426),o=n(21833),i=n(38982),a=n(96942),u=n(86953),c=n(69193),s=n(47210).f,l=n(47931),f=n(16030),p=n(96641),d=n(84228),h=n(60303),y=n(76434),v=n(92446),m=n(79061),g=n(34863),b=n(58319).enforce,_=n(18807),w=n(39189),S=n(99121),C=n(90324),E=w("match"),I=o.RegExp,O=I.prototype,P=o.SyntaxError,T=i(O.exec),A=i("".charAt),x=i("".replace),k=i("".indexOf),R=i("".slice),M=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,j=/a/g,N=/a/g,D=new I(j)!==j,L=h.MISSED_STICKY,z=h.UNSUPPORTED_Y;if(a("RegExp",r&&(!D||L||S||C||m((function(){return N[E]=!1,I(j)!=j||I(N)==N||"/a/i"!=I(j,"i")}))))){for(var U=function(t,e){var n,r,o,i,a,s,h=l(O,this),y=f(t),v=void 0===e,m=[],_=t;if(!h&&y&&v&&t.constructor===U)return t;if((y||l(O,t))&&(t=t.source,v&&(e=d(_))),t=void 0===t?"":p(t),e=void 0===e?"":p(e),_=t,S&&"dotAll"in j&&(r=!!e&&k(e,"s")>-1)&&(e=x(e,/s/g,"")),n=e,L&&"sticky"in j&&(o=!!e&&k(e,"y")>-1)&&z&&(e=x(e,/y/g,"")),C&&(i=function(t){for(var e,n=t.length,r=0,o="",i=[],a={},u=!1,c=!1,s=0,l="";r<=n;r++){if("\\"===(e=A(t,r)))e+=A(t,++r);else if("]"===e)u=!1;else if(!u)switch(!0){case"["===e:u=!0;break;case"("===e:T(M,R(t,r+1))&&(r+=2,c=!0),o+=e,s++;continue;case">"===e&&c:if(""===l||g(a,l))throw new P("Invalid capture group name");a[l]=!0,i[i.length]=[l,s],c=!1,l="";continue}c?l+=e:o+=e}return[o,i]}(t),t=i[0],m=i[1]),a=u(I(t,e),h?this:O,U),(r||o||m.length)&&(s=b(a),r&&(s.dotAll=!0,s.raw=U(function(t){for(var e,n=t.length,r=0,o="",i=!1;r<=n;r++)"\\"!==(e=A(t,r))?i||"."!==e?("["===e?i=!0:"]"===e&&(i=!1),o+=e):o+="[\\s\\S]":o+=e+A(t,++r);return o}(t),n)),o&&(s.sticky=!0),m.length&&(s.groups=m)),t!==_)try{c(a,"source",""===_?"(?:)":_)}catch(t){}return a},F=s(I),B=0;F.length>B;)y(U,I,F[B++]);O.constructor=U,U.prototype=O,v(o,"RegExp",U,{constructor:!0})}_("RegExp")},18489:(t,e,n)=>{"use strict";var r=n(58288),o=n(74989);r({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},88315:(t,e,n)=>{"use strict";var r=n(92684).PROPER,o=n(92446),i=n(90649),a=n(96641),u=n(79061),c=n(84228),s="toString",l=RegExp.prototype[s],f=u((function(){return"/a/b"!=l.call({source:"a",flags:"b"})})),p=r&&l.name!=s;(f||p)&&o(RegExp.prototype,s,(function(){var t=i(this);return"/"+a(t.source)+"/"+a(c(t))}),{unsafe:!0})},58055:(t,e,n)=>{"use strict";n(35365)("Set",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(49720))},65669:(t,e,n)=>{n(58055)},52063:(t,e,n)=>{"use strict";var r,o=n(58288),i=n(46526),a=n(77637).f,u=n(99536),c=n(96641),s=n(15425),l=n(29412),f=n(59494),p=n(59785),d=i("".endsWith),h=i("".slice),y=Math.min,v=f("endsWith");o({target:"String",proto:!0,forced:!(!p&&!v&&(r=a(String.prototype,"endsWith"),r&&!r.writable)||v)},{endsWith:function(t){var e=c(l(this));s(t);var n=arguments.length>1?arguments[1]:void 0,r=e.length,o=void 0===n?r:y(u(n),r),i=c(t);return d?d(e,i,o):h(e,o-i.length,o)===i}})},35157:(t,e,n)=>{"use strict";var r=n(58288),o=n(38982),i=n(15425),a=n(29412),u=n(96641),c=n(59494),s=o("".indexOf);r({target:"String",proto:!0,forced:!c("includes")},{includes:function(t){return!!~s(u(a(this)),u(i(t)),arguments.length>1?arguments[1]:void 0)}})},25766:(t,e,n)=>{"use strict";var r=n(65877).charAt,o=n(96641),i=n(58319),a=n(49626),u=n(42579),c="String Iterator",s=i.set,l=i.getterFor(c);a(String,"String",(function(t){s(this,{type:c,string:o(t),index:0})}),(function(){var t,e=l(this),n=e.string,o=e.index;return o>=n.length?u(void 0,!0):(t=r(n,o),e.index+=t.length,u(t,!1))}))},54232:(t,e,n)=>{"use strict";var r=n(58288),o=n(68662);r({target:"String",proto:!0,forced:n(15927)("link")},{link:function(t){return o(this,"a","href",t)}})},95743:(t,e,n)=>{"use strict";var r=n(44931),o=n(35146),i=n(90649),a=n(40899),u=n(99536),c=n(96641),s=n(29412),l=n(4224),f=n(78839),p=n(47160);o("match",(function(t,e,n){return[function(e){var n=s(this),o=a(e)?void 0:l(e,t);return o?r(o,e,n):new RegExp(e)[t](c(n))},function(t){var r=i(this),o=c(t),a=n(e,r,o);if(a.done)return a.value;if(!r.global)return p(r,o);var s=r.unicode;r.lastIndex=0;for(var l,d=[],h=0;null!==(l=p(r,o));){var y=c(l[0]);d[h]=y,""===y&&(r.lastIndex=f(o,u(r.lastIndex),s)),h++}return 0===h?null:d}]}))},7771:(t,e,n)=>{"use strict";var r=n(58288),o=n(8439).end;r({target:"String",proto:!0,forced:n(96929)},{padEnd:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},20902:(t,e,n)=>{"use strict";var r=n(58288),o=n(8439).start;r({target:"String",proto:!0,forced:n(96929)},{padStart:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},77071:(t,e,n)=>{n(58288)({target:"String",proto:!0},{repeat:n(20471)})},53618:(t,e,n)=>{"use strict";var r=n(33247),o=n(44931),i=n(38982),a=n(35146),u=n(79061),c=n(90649),s=n(11055),l=n(40899),f=n(91129),p=n(99536),d=n(96641),h=n(29412),y=n(78839),v=n(4224),m=n(34032),g=n(47160),b=n(39189)("replace"),_=Math.max,w=Math.min,S=i([].concat),C=i([].push),E=i("".indexOf),I=i("".slice),O="$0"==="a".replace(/./,"$0"),P=!!/./[b]&&""===/./[b]("a","$0");a("replace",(function(t,e,n){var i=P?"$":"$0";return[function(t,n){var r=h(this),i=l(t)?void 0:v(t,b);return i?o(i,t,r,n):o(e,d(r),t,n)},function(t,o){var a=c(this),u=d(t);if("string"==typeof o&&-1===E(o,i)&&-1===E(o,"$<")){var l=n(e,a,u,o);if(l.done)return l.value}var h=s(o);h||(o=d(o));var v=a.global;if(v){var b=a.unicode;a.lastIndex=0}for(var O=[];;){var P=g(a,u);if(null===P)break;if(C(O,P),!v)break;""===d(P[0])&&(a.lastIndex=y(u,p(a.lastIndex),b))}for(var T,A="",x=0,k=0;k=x&&(A+=I(u,x,M)+z,x=M+R.length)}return A+I(u,x)}]}),!!u((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$")}))||!O||P)},27188:(t,e,n)=>{"use strict";var r=n(44931),o=n(35146),i=n(90649),a=n(40899),u=n(29412),c=n(45448),s=n(96641),l=n(4224),f=n(47160);o("search",(function(t,e,n){return[function(e){var n=u(this),o=a(e)?void 0:l(e,t);return o?r(o,e,n):new RegExp(e)[t](s(n))},function(t){var r=i(this),o=s(t),a=n(e,r,o);if(a.done)return a.value;var u=r.lastIndex;c(u,0)||(r.lastIndex=0);var l=f(r,o);return c(r.lastIndex,u)||(r.lastIndex=u),null===l?-1:l.index}]}))},11062:(t,e,n)=>{"use strict";var r=n(33247),o=n(44931),i=n(38982),a=n(35146),u=n(90649),c=n(40899),s=n(16030),l=n(29412),f=n(46439),p=n(78839),d=n(99536),h=n(96641),y=n(4224),v=n(10301),m=n(47160),g=n(74989),b=n(60303),_=n(79061),w=b.UNSUPPORTED_Y,S=4294967295,C=Math.min,E=[].push,I=i(/./.exec),O=i(E),P=i("".slice);a("split",(function(t,e,n){var i;return i="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var i=h(l(this)),a=void 0===n?S:n>>>0;if(0===a)return[];if(void 0===t)return[i];if(!s(t))return o(e,i,t,a);for(var u,c,f,p=[],d=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),y=0,m=new RegExp(t.source,d+"g");(u=o(g,m,i))&&!((c=m.lastIndex)>y&&(O(p,P(i,y,u.index)),u.length>1&&u.index=a));)m.lastIndex===u.index&&m.lastIndex++;return y===i.length?!f&&I(m,"")||O(p,""):O(p,P(i,y)),p.length>a?v(p,0,a):p}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:o(e,this,t,n)}:e,[function(e,n){var r=l(this),a=c(e)?void 0:y(e,t);return a?o(a,e,r,n):o(i,h(r),e,n)},function(t,r){var o=u(this),a=h(t),c=n(i,o,a,r,i!==e);if(c.done)return c.value;var s=f(o,RegExp),l=o.unicode,y=(o.ignoreCase?"i":"")+(o.multiline?"m":"")+(o.unicode?"u":"")+(w?"g":"y"),v=new s(w?"^(?:"+o.source+")":o,y),g=void 0===r?S:r>>>0;if(0===g)return[];if(0===a.length)return null===m(v,a)?[a]:[];for(var b=0,_=0,E=[];_{"use strict";var r,o=n(58288),i=n(46526),a=n(77637).f,u=n(99536),c=n(96641),s=n(15425),l=n(29412),f=n(59494),p=n(59785),d=i("".startsWith),h=i("".slice),y=Math.min,v=f("startsWith");o({target:"String",proto:!0,forced:!(!p&&!v&&(r=a(String.prototype,"startsWith"),r&&!r.writable)||v)},{startsWith:function(t){var e=c(l(this));s(t);var n=u(y(arguments.length>1?arguments[1]:void 0,e.length)),r=c(t);return d?d(e,r,n):h(e,n,n+r.length)===r}})},63632:(t,e,n)=>{n(93795);var r=n(58288),o=n(92024);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==o},{trimEnd:o})},91360:(t,e,n)=>{var r=n(58288),o=n(10409);r({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==o},{trimLeft:o})},93795:(t,e,n)=>{var r=n(58288),o=n(92024);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==o},{trimRight:o})},76241:(t,e,n)=>{n(91360);var r=n(58288),o=n(10409);r({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==o},{trimStart:o})},948:(t,e,n)=>{"use strict";var r=n(58288),o=n(92572).trim;r({target:"String",proto:!0,forced:n(4160)("trim")},{trim:function(){return o(this)}})},43366:(t,e,n)=>{n(1749)("asyncIterator")},11399:(t,e,n)=>{"use strict";var r=n(58288),o=n(21833),i=n(44931),a=n(38982),u=n(59785),c=n(4426),s=n(12289),l=n(79061),f=n(34863),p=n(47931),d=n(90649),h=n(4395),y=n(50243),v=n(96641),m=n(52302),g=n(32814),b=n(80094),_=n(47210),w=n(83744),S=n(68255),C=n(77637),E=n(59143),I=n(2459),O=n(46391),P=n(92446),T=n(61548),A=n(51435),x=n(40693),k=n(43343),R=n(64550),M=n(39189),j=n(2561),N=n(1749),D=n(80236),L=n(49233),z=n(58319),U=n(31567).forEach,F=x("hidden"),B="Symbol",q="prototype",V=z.set,G=z.getterFor(B),H=Object[q],Y=o.Symbol,W=Y&&Y[q],K=o.TypeError,$=o.QObject,Q=C.f,Z=E.f,J=w.f,X=O.f,tt=a([].push),et=A("symbols"),nt=A("op-symbols"),rt=A("wks"),ot=!$||!$[q]||!$[q].findChild,it=c&&l((function(){return 7!=g(Z({},"a",{get:function(){return Z(this,"a",{value:7}).a}})).a}))?function(t,e,n){var r=Q(H,e);r&&delete H[e],Z(t,e,n),r&&t!==H&&Z(H,e,r)}:Z,at=function(t,e){var n=et[t]=g(W);return V(n,{type:B,tag:t,description:e}),c||(n.description=e),n},ut=function(t,e,n){t===H&&ut(nt,e,n),d(t);var r=y(e);return d(n),f(et,r)?(n.enumerable?(f(t,F)&&t[F][r]&&(t[F][r]=!1),n=g(n,{enumerable:m(0,!1)})):(f(t,F)||Z(t,F,m(1,{})),t[F][r]=!0),it(t,r,n)):Z(t,r,n)},ct=function(t,e){d(t);var n=h(e),r=b(n).concat(pt(n));return U(r,(function(e){c&&!i(st,n,e)||ut(t,e,n[e])})),t},st=function(t){var e=y(t),n=i(X,this,e);return!(this===H&&f(et,e)&&!f(nt,e))&&(!(n||!f(this,e)||!f(et,e)||f(this,F)&&this[F][e])||n)},lt=function(t,e){var n=h(t),r=y(e);if(n!==H||!f(et,r)||f(nt,r)){var o=Q(n,r);return!o||!f(et,r)||f(n,F)&&n[F][r]||(o.enumerable=!0),o}},ft=function(t){var e=J(h(t)),n=[];return U(e,(function(t){f(et,t)||f(k,t)||tt(n,t)})),n},pt=function(t){var e=t===H,n=J(e?nt:h(t)),r=[];return U(n,(function(t){!f(et,t)||e&&!f(H,t)||tt(r,et[t])})),r};s||(P(W=(Y=function(){if(p(W,this))throw K("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?v(arguments[0]):void 0,e=R(t),n=function(t){this===H&&i(n,nt,t),f(this,F)&&f(this[F],e)&&(this[F][e]=!1),it(this,e,m(1,t))};return c&&ot&&it(H,e,{configurable:!0,set:n}),at(e,t)})[q],"toString",(function(){return G(this).tag})),P(Y,"withoutSetter",(function(t){return at(R(t),t)})),O.f=st,E.f=ut,I.f=ct,C.f=lt,_.f=w.f=ft,S.f=pt,j.f=function(t){return at(M(t),t)},c&&(T(W,"description",{configurable:!0,get:function(){return G(this).description}}),u||P(H,"propertyIsEnumerable",st,{unsafe:!0}))),r({global:!0,constructor:!0,wrap:!0,forced:!s,sham:!s},{Symbol:Y}),U(b(rt),(function(t){N(t)})),r({target:B,stat:!0,forced:!s},{useSetter:function(){ot=!0},useSimple:function(){ot=!1}}),r({target:"Object",stat:!0,forced:!s,sham:!c},{create:function(t,e){return void 0===e?g(t):ct(g(t),e)},defineProperty:ut,defineProperties:ct,getOwnPropertyDescriptor:lt}),r({target:"Object",stat:!0,forced:!s},{getOwnPropertyNames:ft}),D(),L(Y,B),k[F]=!0},27481:(t,e,n)=>{"use strict";var r=n(58288),o=n(4426),i=n(21833),a=n(38982),u=n(34863),c=n(11055),s=n(47931),l=n(96641),f=n(61548),p=n(14938),d=i.Symbol,h=d&&d.prototype;if(o&&c(d)&&(!("description"in h)||void 0!==d().description)){var y={},v=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:l(arguments[0]),e=s(h,this)?new d(t):void 0===t?d():d(t);return""===t&&(y[e]=!0),e};p(v,d),v.prototype=h,h.constructor=v;var m="Symbol(test)"==String(d("test")),g=a(h.valueOf),b=a(h.toString),_=/^Symbol\((.*)\)[^)]+$/,w=a("".replace),S=a("".slice);f(h,"description",{configurable:!0,get:function(){var t=g(this);if(u(y,t))return"";var e=b(t),n=m?S(e,7,-1):w(e,_,"$1");return""===n?void 0:n}}),r({global:!0,constructor:!0,forced:!0},{Symbol:v})}},51928:(t,e,n)=>{var r=n(58288),o=n(78797),i=n(34863),a=n(96641),u=n(51435),c=n(5462),s=u("string-to-symbol-registry"),l=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!c},{for:function(t){var e=a(t);if(i(s,e))return s[e];var n=o("Symbol")(e);return s[e]=n,l[n]=e,n}})},90105:(t,e,n)=>{n(1749)("iterator")},91621:(t,e,n)=>{n(11399),n(51928),n(88794),n(81172),n(69047)},88794:(t,e,n)=>{var r=n(58288),o=n(34863),i=n(30907),a=n(79269),u=n(51435),c=n(5462),s=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!c},{keyFor:function(t){if(!i(t))throw TypeError(a(t)+" is not a symbol");if(o(s,t))return s[t]}})},11138:(t,e,n)=>{var r=n(1749),o=n(80236);r("toPrimitive"),o()},81676:(t,e,n)=>{"use strict";var r,o=n(1566),i=n(21833),a=n(38982),u=n(14101),c=n(89277),s=n(35365),l=n(42715),f=n(96692),p=n(58319).enforce,d=n(79061),h=n(74528),y=Object,v=Array.isArray,m=y.isExtensible,g=y.isFrozen,b=y.isSealed,_=y.freeze,w=y.seal,S={},C={},E=!i.ActiveXObject&&"ActiveXObject"in i,I=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},O=s("WeakMap",I,l),P=O.prototype,T=a(P.set);if(h)if(E){r=l.getConstructor(I,"WeakMap",!0),c.enable();var A=a(P.delete),x=a(P.has),k=a(P.get);u(P,{delete:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),A(this,t)||e.frozen.delete(t)}return A(this,t)},has:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),x(this,t)||e.frozen.has(t)}return x(this,t)},get:function(t){if(f(t)&&!m(t)){var e=p(this);return e.frozen||(e.frozen=new r),x(this,t)?k(this,t):e.frozen.get(t)}return k(this,t)},set:function(t,e){if(f(t)&&!m(t)){var n=p(this);n.frozen||(n.frozen=new r),x(this,t)?T(this,t,e):n.frozen.set(t,e)}else T(this,t,e);return this}})}else o&&d((function(){var t=_([]);return T(new O,t,1),!g(t)}))&&u(P,{set:function(t,e){var n;return v(t)&&(g(t)?n=S:b(t)&&(n=C)),T(this,t,e),n==S&&_(t),n==C&&w(t),this}})},11530:(t,e,n)=>{n(81676)},44594:(t,e,n)=>{var r=n(21833),o=n(4774),i=n(4474),a=n(9877),u=n(69193),c=function(t){if(t&&t.forEach!==a)try{u(t,"forEach",a)}catch(e){t.forEach=a}};for(var s in o)o[s]&&c(r[s]&&r[s].prototype);c(i)},92947:(t,e,n)=>{var r=n(21833),o=n(4774),i=n(4474),a=n(14718),u=n(69193),c=n(39189),s=c("iterator"),l=c("toStringTag"),f=a.values,p=function(t,e){if(t){if(t[s]!==f)try{u(t,s,f)}catch(e){t[s]=f}if(t[l]||u(t,l,e),o[e])for(var n in a)if(t[n]!==a[n])try{u(t,n,a[n])}catch(e){t[n]=a[n]}}};for(var d in o)p(r[d]&&r[d].prototype,d);p(i,"DOMTokenList")},18342:(t,e,n)=>{"use strict";var r=n(58288),o=n(44931);r({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return o(URL.prototype.toString,this)}})}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={id:r,loaded:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t);var r={};return(()=>{"use strict";n.r(r),n.d(r,{createCheckoutButtonInitializer:()=>Eh,createTimeout:()=>o.createTimeout});var t={};n.r(t),n.d(t,{createAmazonPayV2ButtonStrategy:()=>yl,createApplePayButtonStrategy:()=>Bl,createBoltButtonStrategy:()=>ef,createBraintreeVenmoButtonStrategy:()=>mf,createBraintreeVisaCheckoutButtonStrategy:()=>cf,createGooglePayAdyenV2ButtonStrategy:()=>mp,createGooglePayAdyenV3ButtonStrategy:()=>gp,createGooglePayAuthorizeDotNetButtonStrategy:()=>Sp,createGooglePayBraintreeButtonStrategy:()=>op,createGooglePayCheckoutComButtonStrategy:()=>xp,createGooglePayCybersourceButtonStrategy:()=>jp,createGooglePayOrbitalButtonStrategy:()=>zp,createGooglePayPayPalCommerceButtonStrategy:()=>vp,createGooglePayStripeButtonStrategy:()=>Zp,createGooglePayTdOnlineMartButtonStrategy:()=>cd,createGooglePayWorldpayAccessButtonStrategy:()=>ed,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>sh,createPayPalCommerceButtonStrategy:()=>Ud,createPayPalCommerceCreditButtonStrategy:()=>Zd,createPayPalCommerceVenmoButtonStrategy:()=>rh,createPaypalExpressButtonStrategy:()=>Ch});var e,o=n(9285),i=n(74152),a=(n(90291),n(99840)),u=(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)},function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)});const c=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return u(e,t),e}(Error);var s=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),l={body:{},headers:{},status:0},f=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,u=e||l,c=u.body,s=u.headers,f=u.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=s,a.status=f,a.errors=i||[],a}return s(e,t),e}(c);const p=f;var d=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const h=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return d(e,t),e}(p);n(18864),n(68461);var y,v=(y=function(t,e){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},y(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}y(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return v(e,t),e}(Error);var g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),b={body:{},headers:{},status:0},_=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,u=e||b,c=u.body,s=u.headers,l=u.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=s,a.status=l,a.errors=i||[],a}return g(e,t),e}(m);const w=_;var S=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const C=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return S(e,t),e}(w);n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(11062),n(92947);var E=n(45550),I=(n(98556),n(57188),n(80404),n(44396),function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o-1){var o=n[r];return r>0&&(n.splice(r,1),n.unshift(o)),o.value}return or}return{get:r,put:function(e,o){r(e)===or&&(n.unshift({key:e,value:o}),n.length>t&&n.pop())},getEntries:function(){return n},clear:function(){n=[]}}}(c,l);function p(){var e=f.get(arguments);if(e===or){if(e=t.apply(null,arguments),s){var n=f.getEntries().find((function(t){return s(t.value,e)}));n&&(e=n.value)}f.put(arguments,e)}return e}return p.clearCache=function(){return f.clear()},p}function ur(t){return ur="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ur(t)}function cr(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r0}})),Y=lr(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===br||t()===_r}})),(0,tr.B4)((function(t,e){return{getPaymentId:L({checkout:t,order:e}),getPaymentIdOrThrow:z({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:F({checkout:t,order:e}),getPaymentToken:B({checkout:t,order:e}),getPaymentTokenOrThrow:q({checkout:t,order:e}),getPaymentRedirectUrl:V({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:G({checkout:t,order:e}),isPaymentDataRequired:H({checkout:t,order:e}),isPaymentDataSubmitted:Y({checkout:t,order:e})}}))),Et=function(){var t=lr((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=lr((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,tr.B4)((function(n){return void 0===n&&(n=Cr),{getApplyError:t(n),isApplying:e(n)}}))}(),It=function(){var t=lr((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=lr((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,tr.B4)((function(n){return void 0===n&&(n=Gn),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Ot=(W=lr((function(t){return t.data}),(function(t){return function(){return t}})),K=lr((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),$=lr((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,tr.B4)((function(t){return void 0===t&&(t=jn),{getEmail:W(t),getSendError:K(t),isSending:$(t)}}))),Pt=function(){var t=lr((function(t){return t.data}),(function(t){return function(){return t}})),e=lr((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=lr((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=lr((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,tr.B4)((function(o){return void 0===o&&(o=Xt),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n=Z(t.billingAddress),r=J(t.cart),o=X(t.checkoutButton),i=et(t.countries),a=nt(t.coupons),u=rt(t.customer),c=ot(t.customerStrategies),s=Pt(t.extensions),l=ut(t.formFields),f=it(t.giftCertificates),p=at(t.instruments),d=wt(t.orderBillingAddress),h=st(t.paymentMethods),y=pt(t.paymentProviderCustomer),v=lt(t.paymentStrategies),m=ft(t.pickupOptions),g=dt(t.remoteCheckout),b=yt(t.consignments),_=vt(t.shippingCountries),w=mt(t.shippingStrategies),S=It(t.subscriptions),C=Et(t.storeCredit),E=Ot(t.signInEmail),I=gt(t.consignments,r),O=bt(t.checkout,n,r,I,a,u,f),P=_t(t.order,d,a),T=St(O,P),A={billingAddress:n,cart:r,checkout:O,checkoutButton:o,config:tt(t.config,t.formFields),consignments:I,countries:i,coupons:a,customer:u,customerStrategies:c,extensions:s,form:l,giftCertificates:f,instruments:p,order:P,orderBillingAddress:d,payment:T,paymentMethods:h,paymentProviderCustomer:y,paymentStrategies:v,pickupOptions:m,remoteCheckout:g,shippingAddress:b,shippingCountries:_,shippingStrategies:w,signInEmail:E,subscriptions:S,storeCredit:C};return e.shouldWarnMutation?function(t){return Object.keys(t).reduce((function(e,n){return e[n]=hr(t[n]),e}),{})}(A):A}}var Or=function(){return Or=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadPaymentMethod",null),t}();const Lr=Dr;var zr;!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(zr||(zr={}));const Ur=zr;var Fr="This API endpoint is for internal use only and may change in the future",Br={"X-Checkout-SDK-Version":"1.696.0"},qr=function(){return qr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new wo(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,u="/api/storefront/checkout/".concat(t),c=So({Accept:Ur.JsonV1},Br);return this._requestSender.put(u,{params:{include:go(bo,i)},body:e,headers:c,timeout:a})},t}();const Eo=Co,Io=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,E.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return"".concat(t.id).localeCompare("".concat(e.id))})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return"".concat(t.productId).concat(t.variantId).localeCompare("".concat(e.productId).concat(e.variantId))})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}();var Oo=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Po=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return Oo(e,t),e}(m),To=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new nr(Xn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new Io;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new Po(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,E.isEqual)((0,E.map)(t,"code"),(0,E.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,E.isEqual)((0,E.map)(t,"code"),(0,E.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,o=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:o}},t}();function Ao(t){return Ao="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ao(t)}const xo=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return Tr.c.create((function(n){n.next((0,a.VP)(dt.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,a.VP)(dt.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,a.fQ)(dt.LoadConfigFailed,t))}))}))},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":Ao(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadConfig",null),t}();var ko=function(){return ko=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new wo(t);throw t}))},t}();const Mo=Ro;var jo=n(45893);function No(t){return No="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},No(t)}function Do(t){var e=t;return"object"===No(e)&&"object"===No(e.payload)&&"string"==typeof e.payload.token}var Lo=function(){return Lo=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([Rr],t.prototype,"loadFormFields",null),t}();const Go=Vo;var Ho=function(){return Ho=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&ui(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([pi],t.prototype,"_handleMessage",null),t}();const vi=yi;var mi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const gi=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return mi(e,t),e}(m);var bi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const _i=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return bi(e,t),e}(m);var wi=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Si=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return wi(e,t),e}(m);var Ci=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function u(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}c((r=r.apply(t,e||[])).next())}))},Ei=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!u?a:"".concat(a," ").concat("/"," ").concat(u)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const Na=ja;var Da=n(35647);const La=function(){function t(){}return t.prototype.format=function(t){var e=(0,Da.number)(t).card;if(!e)return t;var n=(0,E.max)((0,Da.creditCardType)(t).map((function(t){return(0,E.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,Da.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();n(54232);var za=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new nr(Xn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,E.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"===eu(t)&&"address"in t},t}();const iu=ou;var au=function(){return au=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([tc],t)}();function rc(t){return rc="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rc(t)}const oc=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":rc(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([tc],t)}();function ic(t){return{errors:new nc(t),statuses:new oc(t)}}function ac(t){return ac="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ac(t)}var uc=function(){return uc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([pi],t)}();const sc=cc;var lc=function(){return lc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t}function $c(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function Qc(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var Zc=function(){return Zc=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?o:i[0]:"en_us"}function hs(t){return hs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hs(t)}const ys=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new ii('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new nr(Xn.MissingPaymentMethod);var o={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ds(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(o)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,o=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new nr(Xn.MissingPaymentMethod);if(!o)throw new ii("Unable to retrieve store configuration");var i=document.createElement("input");if(i.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",u=r.initializationData.checkoutId,c=["locale=".concat(ds(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(u)];i.src=["https://".concat(a,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),c.join("&")].join("?")}else i.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(i),i.addEventListener("click",this._handleWalletButtonClick),i},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new nr(Xn.MissingCheckout);if(!n)throw new nr(Xn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat("cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new Ri(Pi.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"===("undefined"==typeof Reflect?"undefined":hs(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([pi],t.prototype,"_handleWalletButtonClick",null),t}();var vs=function(){return vs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===bs()&&Is.warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var u=a[0];if(u&&u.token)return u.token;if(this._useFallback){var c=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const Ps=Os;var Ts=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const As=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Ts(e,t),e}(c);var xs,ks=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(xs||(xs={}));const Rs=function(t){function e(e){var n=t.call(this,function(t){switch(t){case xs.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case xs.MissingCart:return"Unable to proceed because cart data is unavailable.";case xs.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case xs.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case xs.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case xs.MissingCheckoutConfig:case xs.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case xs.MissingOrder:return"Unable to proceed because order data is unavailable.";case xs.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case xs.MissingPayment:return"Unable to proceed because payment data is unavailable.";case xs.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case xs.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case xs.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return ks(e,t),e}(c);function Ms(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,E.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function js(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Ns,Ds=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Ns||(Ns={}));const Ls=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Ns.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Ns.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Ns.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Ns.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return Ds(e,t),e}(c);var zs,Us,Fs,Bs,qs,Vs,Gs={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(zs||(zs={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(Us||(Us={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(Fs||(Fs={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(Bs||(Bs={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(qs||(qs={})),function(t){t.C0001="C0001"}(Vs||(Vs={}));var Hs=function(){return Hs=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:s,merchantCapabilities:p,supportedNetworks:d,lineItems:[],total:h?{label:u,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:u,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(h)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var v=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return v.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=v}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return Dl(r,void 0,void 0,(function(){var r;return Ll(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return Dl(r,void 0,void 0,(function(){var t;return Ll(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Al;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return Dl(r,void 0,void 0,(function(){return Ll(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return Dl(this,void 0,void 0,(function(){var n,r;return Ll(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Rs(xs.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new tl;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Rs(xs.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return Dl(this,void 0,void 0,(function(){var o,i,a,u,c,s,l,f,p,d,h,y;return Ll(this,(function(v){switch(v.label){case 0:o=this._transformContactToAddress(n.shippingContact),v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return v.sent(),[3,4];case 3:throw v.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,u=i.getCheckoutOrThrow(),c=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,s=u.consignments[0].availableShippingOptions,l=null==s?void 0:s.find((function(t){return t.id===c})),f=null==s?void 0:s.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:"".concat(l.cost.toFixed(a)),detail:l.additionalDescription,identifier:l.id}]:[],f&&zl(zl([],f.filter((function(t){return t.isRecommended})),!0),f.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(s instanceof Array))throw new Error("Shipping options not available.");if(0===s.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(u.grandTotal.toFixed(a))},[]),[2];d=s.find((function(t){return t.isRecommended})),h=d?d.id:s[0].id,y=l?l.id:h,v.label=5;case 5:return v.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return v.sent(),[3,8];case 7:throw v.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),u=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(u.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(u,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return Dl(this,void 0,void 0,(function(){var r,o,i,a;return Ll(this,(function(u){switch(u.label){case 0:r=n.shippingMethod.identifier,u.label=1;case 1:return u.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return u.sent(),[3,4];case 3:throw u.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return Dl(this,void 0,void 0,(function(){return Ll(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return Dl(this,void 0,void 0,(function(){var n;return Ll(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return Dl(this,void 0,void 0,(function(){var o,i,a,u,c,s,l,f,p,d,h,y,v;return Ll(this,(function(m){switch(m.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,u=o.shippingContact,c=this._paymentIntegrationService.getState(),s=c.getCartOrThrow(),l=s.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==xl.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:f=m.sent(),m.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:f,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},d=this._transformContactToAddress(a),h=this._transformContactToAddress(u),y=null==u?void 0:u.emailAddress,v=(null==u?void 0:u.phoneNumber)||"",m.label=3;case 3:return m.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Nl(Nl({},d),{email:y,phone:v}))];case 4:return m.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,6];case 5:m.sent(),m.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return m.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return m.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw m.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return Dl(this,void 0,void 0,(function(){return Ll(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return Dl(this,void 0,void 0,(function(){var t,e;return Ll(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(xl.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(xl.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const Fl=Ul,Bl=Js((function(t){var e=t.getState().getHost;return new Fl((0,o.createRequestSender)({host:e()}),t,new Rl,new Pl(new Sc((0,Hr.vQ)(),window)))}),[{id:"applepay"}]);var ql=n(80652),Vl=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Gl=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return Vl(e,t),e}(c);var Hl,Yl,Wl;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(Hl||(Hl={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(Yl||(Yl={})),function(t){t.Pill="pill",t.Rect="rect"}(Wl||(Wl={}));var Kl=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,u,c,s,l,f,p,d;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const uf=af,cf=Js((function(t){var e=window,n=new Pl(new Sc((0,Hr.vQ)(),e));return new uf(t,(0,i.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function sf(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function lf(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([pi],t)}();var wf,Sf,Cf,Ef,If,Of,Pf,Tf;function Af(t){return t in Of}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(wf||(wf={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(Sf||(Sf={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Cf||(Cf={})),function(t){t.pill="pill",t.rect="rect"}(Ef||(Ef={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(If||(If={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(Of||(Of={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(Pf||(Pf={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Tf||(Tf={}));var xf=function(){return xf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0))},t.prototype._mapToAddressRequestBody=function(t,e,n){var r=t.name,o=t.address1,i=t.address2,a=t.address3,u=t.locality,c=t.administrativeArea,s=t.countryCode,l=t.postalCode,f=t.phoneNumber,p=this._getFirstAndLastName(r);return{firstName:p[0],lastName:p[1],company:e,address1:o,address2:"".concat(i," ").concat(a).trim(),city:u||c,stateOrProvince:c,stateOrProvinceCode:c,countryCode:s,postalCode:l,phone:f||n,customFields:[]}},t.prototype._getFirstAndLastName=function(t){var e=t.split(" ");return 1===e.length?[t,""]:[e.slice(0,-1).join(" "),e[e.length-1]]},t.prototype._getCurrencyCodeOrThrow=function(){return js(this._currencyCode,(function(){return new As('Unable to initialize payment because "options.currencyCode" argument is not provided.')}))},t.prototype._getGooglePayShippingOption=function(t){var e,n=t.id,r=t.cost;return{id:n,label:t.description,description:(null===(e=this._currencyService)||void 0===e?void 0:e.toCustomerCurrency(r))||r}},t}();const jf=Mf;var Nf=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Df=function(){return Df=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":R.length>0?R:void 0,commit:_,components:dp(dp(["buttons","hosted-fields","messages","payment-fields","legal"],j,!0),E,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=lp(lp({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const yp=hp,vp=Js((function(t){return new Kf(t,new Xf(rp(),new sp(t,new yp((0,Hr.vQ)())),(0,o.createRequestSender)(),(0,i.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]),mp=Js((function(t){var e=(0,o.createRequestSender)();return new Kf(t,new Xf(rp(),new jf("adyen",t),e,(0,i.createFormPoster)()))}),[{id:"googlepayadyenv2"}]),gp=Js((function(t){var e=(0,o.createRequestSender)();return new Kf(t,new Xf(rp(),new jf("adyen",t),e,(0,i.createFormPoster)()))}),[{id:"googlepayadyenv3"}]);var bp=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),_p=function(t){function e(e){return t.call(this,"authorizenet",e)||this}return bp(e,t),e.prototype.mapToExternalCheckoutData=function(e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const wd=_d;var Sd=function(){return Sd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?j:void 0,"disable-funding":M.length>0?M:void 0,commit:_,components:xd(xd(["buttons","hosted-fields","payment-fields","legal"],k,!0),R,!0),currency:e,intent:a},h&&{"buyer-country":s}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Pd(Pd({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Rd=kd,Md=function(t){var e=t.getState().getHost;return new wd((0,i.createFormPoster)(),t,new Od((0,o.createRequestSender)({host:e()})),new Rd((0,Hr.vQ)()))};var jd=function(){return jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=l.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Nd(this,void 0,void 0,(function(){var e,n,r;return Dd(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Nd(this,void 0,void 0,(function(){var e,n;return Dd(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const zd=Ld,Ud=Js((function(t){return new zd(t,Md(t))}),[{id:"paypalcommerce"}]);var Fd=function(){return Fd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?d:void 0,"disable-funding":h.length>0?h:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},c&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":u,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Rs(xs.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,u=n.buyerCountry;return{options:Fd({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":u}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Fd(Fd({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Gd=Vd,Hd=function(t){var e=t.styles,n={};return e.color&&(n.color=e.color),e.layout&&(n.layout=e.layout),(e["logo-type"]||e["logo-position"])&&(n.logo={},e["logo-type"]&&(n.logo.type=e["logo-type"]),e["logo-position"]&&(n.logo.position=e["logo-position"])),e.ratio&&(n.ratio=e.ratio),(e["text-color"]||e["text-size"])&&(n.text={},e["text-color"]&&(n.text.color=e["text-color"]),e["text-size"]&&(n.text.size=+e["text-size"])),n};var Yd=function(){return Yd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(s=l.sent()))throw new Error(s);throw s;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Wd(this,void 0,void 0,(function(){var e,n,r;return Kd(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Wd(this,void 0,void 0,(function(){var e,n;return Kd(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?Hd(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const Qd=$d,Zd=Js((function(t){return new Qd(t,Md(t),new Gd((0,Hr.Hb)()))}),[{id:"paypalcommercecredit"}]);var Jd=function(){return Jd=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]{"use strict";var t={483:t=>{t.exports=require("iframe-resizer")},405:t=>{t.exports=require("iframe-resizer/js/iframeResizer.contentWindow")}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,n),i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};n.r(r),n.d(r,{ExtensionCommandType:()=>yd,createBodlService:()=>JT,createBraintreeAnalyticTracker:()=>zT,createCheckoutButtonInitializer:()=>Lk,createCheckoutService:()=>dE,createCurrencyService:()=>yT,createEmbeddedCheckoutMessenger:()=>iT,createLanguageService:()=>hT,createPayPalCommerceAnalyticTracker:()=>LT,createStepTracker:()=>kT,createStoredCardHostedFormService:()=>UT,createTimeout:()=>s.createTimeout,embedCheckout:()=>$k});var o={};n.r(o),n.d(o,{createAmazonPayV2CustomerStrategy:()=>pe,createApplePayCustomerStrategy:()=>Ye,createBoltCustomerStrategy:()=>yn,createBraintreeFastlaneCustomerStrategy:()=>ir,createBraintreePaypalCreditCustomerStrategy:()=>Un,createBraintreePaypalCustomerStrategy:()=>Rn,createBraintreeVisaCheckoutCustomerStrategy:()=>dr,createGooglePayAdyenV2CustomerStrategy:()=>Qr,createGooglePayAdyenV3CustomerStrategy:()=>$r,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ro,createGooglePayBnzCustomerStrategy:()=>bo,createGooglePayBraintreeCustomerStrategy:()=>Jo,createGooglePayCheckoutComCustomerStrategy:()=>fo,createGooglePayCybersourceCustomerStrategy:()=>go,createGooglePayOrbitalCustomerStrategy:()=>Co,createGooglePayPayPalCommerceCustomerStrategy:()=>si,createGooglePayStripeCustomerStrategy:()=>No,createGooglePayStripeUpeCustomerStrategy:()=>Fo,createGooglePayTdOnlineMartCustomerStrategy:()=>fi,createGooglePayWorldpayAccessCustomerStrategy:()=>Uo,createPayPalCommerceCreditCustomerStrategy:()=>ta,createPayPalCommerceCustomerStrategy:()=>Ki,createPayPalCommerceFastlaneCustomerStrategy:()=>xa,createPayPalCommerceVenmoCustomerStrategy:()=>aa,createStripeUPECustomerStrategy:()=>Wa});var i={};n.r(i),n.d(i,{createAdyenV2PaymentStrategy:()=>Wd,createAdyenV3PaymentStrategy:()=>ep,createAffirmPaymentStrategy:()=>cp,createAfterpayPaymentStrategy:()=>bp,createAmazonPayV2PaymentStrategy:()=>Ip,createApplePayPaymentStrategy:()=>Tp,createBlueSnapDirectAPMPaymentStrategy:()=>lh,createBlueSnapDirectCreditCardPaymentStrategy:()=>ah,createBlueSnapV2PaymentStrategy:()=>vh,createBoltPaymentStrategy:()=>kh,createBraintreeAchPaymentStrategy:()=>Nh,createBraintreeFastlanePaymentStrategy:()=>hf,createBraintreeLocalMethodsPaymentStrategy:()=>of,createBraintreePaypalPaymentStrategy:()=>Qh,createCheckoutComAPMPaymentStrategy:()=>$f,createCheckoutComCreditCardPaymentStrategy:()=>Ff,createCheckoutComFawryPaymentStrategy:()=>Af,createCheckoutComIdealPaymentStrategy:()=>Yf,createCheckoutComSepaPaymentStrategy:()=>qf,createClearpayPaymentStrategy:()=>sy,createCreditCardPaymentStrategy:()=>cy,createCyberSourcePaymentStrategy:()=>Ay,createCyberSourceV2PaymentStrategy:()=>Ly,createDigitalRiverPaymentStrategy:()=>Jy,createExternalPaymentStrategy:()=>$y,createGooglePayAdyenV2PaymentStrategy:()=>dm,createGooglePayAdyenV3PaymentStrategy:()=>vm,createGooglePayAuthorizeNetPaymentStrategy:()=>gm,createGooglePayBraintreePaymentStrategy:()=>Im,createGooglePayCheckoutComPaymentStrategy:()=>bm,createGooglePayCybersourcePaymentStrategy:()=>wm,createGooglePayOrbitalPaymentStrategy:()=>_m,createGooglePayPPCPPaymentStrategy:()=>Mm,createGooglePayStripePaymentStrategy:()=>Sm,createGooglePayTdOnlineMartPaymentStrategy:()=>zm,createGooglePayWorldpayAccessPaymentStrategy:()=>Cm,createHummPaymentStrategy:()=>Bm,createKlarnaPaymentStrategy:()=>Zm,createKlarnaV2PaymentStrategy:()=>cv,createLegacyPaymentStrategy:()=>dv,createMolliePaymentStrategy:()=>_v,createMonerisPaymentStrategy:()=>Ev,createNoPaymentStrategy:()=>Tv,createOfflinePaymentStrategy:()=>zv,createOffsitePaymentStrategy:()=>Bv,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>sg,createPayPalCommerceCreditCardsPaymentStrategy:()=>mg,createPayPalCommerceCreditPaymentStrategy:()=>Xv,createPayPalCommerceFastlanePaymentStrategy:()=>xg,createPayPalCommercePaymentStrategy:()=>Hv,createPayPalCommerceRatePayPaymentStrategy:()=>Ig,createPayPalCommerceVenmoPaymentStrategy:()=>ng,createPayPalProPaymentStrategy:()=>Lg,createSagePayPaymentStrategy:()=>qg,createSezzlePaymentStrategy:()=>Hg,createSquareV2PaymentStrategy:()=>ib,createStripeOCSPaymentStrategy:()=>jb,createStripeUPEPaymentStrategy:()=>zb,createStripeV3PaymentStrategy:()=>wb,createTDOnlineMartPaymentStrategy:()=>Jb,createWorldpayAccessPaymentStrategy:()=>rw,createZipPaymentStrategy:()=>uw});var a={};n.r(a),n.d(a,{createAmazonPayV2ButtonStrategy:()=>lA,createApplePayButtonStrategy:()=>bA,createBoltButtonStrategy:()=>SA,createBraintreeVenmoButtonStrategy:()=>FA,createBraintreeVisaCheckoutButtonStrategy:()=>AA,createGooglePayAdyenV2ButtonStrategy:()=>HA,createGooglePayAdyenV3ButtonStrategy:()=>WA,createGooglePayAuthorizeDotNetButtonStrategy:()=>YA,createGooglePayBraintreeButtonStrategy:()=>GA,createGooglePayCheckoutComButtonStrategy:()=>KA,createGooglePayCybersourceButtonStrategy:()=>JA,createGooglePayOrbitalButtonStrategy:()=>ZA,createGooglePayPayPalCommerceButtonStrategy:()=>VA,createGooglePayStripeButtonStrategy:()=>XA,createGooglePayTdOnlineMartButtonStrategy:()=>$A,createGooglePayWorldpayAccessButtonStrategy:()=>QA,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>Ck,createPayPalCommerceButtonStrategy:()=>ik,createPayPalCommerceCreditButtonStrategy:()=>dk,createPayPalCommerceVenmoButtonStrategy:()=>vk,createPaypalExpressButtonStrategy:()=>Fk});const s=require("@bigcommerce/request-sender"),c=require("@bigcommerce/script-loader"),u=require("@bigcommerce/data-store"),l=require("lodash"),d=require("rxjs"),p=require("rxjs/operators");function h(t,e,n){return(r=e)&&r.type&&r.error?(0,d.concat)((0,d.of)(e),(0,d.throwError)((0,u.createErrorAction)(t,e.payload,n))):(0,d.throwError)((0,u.createErrorAction)(t,e,n));var r}var f,y=(f=function(t,e){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},f(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}f(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return y(e,t),e}(Error);var v,g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",t[t.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=15]="MissingPaymentStatus",t[t.MissingPaymentToken=16]="MissingPaymentToken",t[t.MissingShippingAddress=17]="MissingShippingAddress"}(v||(v={}));const b=function(t){function e(e){var n=t.call(this,function(t){switch(t){case v.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case v.MissingCart:return"Unable to proceed because cart data is unavailable.";case v.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case v.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case v.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case v.MissingCheckoutConfig:case v.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case v.MissingOrder:return"Unable to proceed because order data is unavailable.";case v.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case v.MissingPayment:return"Unable to proceed because payment data is unavailable.";case v.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case v.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case v.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case v.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return g(e,t),e}(m);var w;!function(t){t.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",t.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",t.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",t.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",t.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",t.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(w||(w={}));var _=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const S=function(t){function e(e){var n=t.call(this,e||"Unable to continue as a guest because the customer is already signed in.")||this;return n.name="UnableToContinueAsGuestError",n.type="unable_to_continue_as_guest",n}return _(e,t),e}(m);var C=function(){return C=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadConfig",null),t}();var X=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Q={body:{},headers:{},status:0},$=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,s=e||Q,c=s.body,u=s.headers,l=s.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=l,a.errors=i||[],a}return X(e,t),e}(m);const tt=$;var et=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const nt=function(t){function e(e){var n=t.call(this,e,{message:e.body.title})||this;return n.name="CheckoutNotAvailableError",n.type="checkout_not_available",n}return et(e,t),e}(tt);var rt="This API endpoint is for internal use only and may change in the future",ot=function(){return ot=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new nt(t);throw t}))},t}();const at=it;var st;!function(t){t.ApplyCouponRequested="APPLY_COUPON_REQUESTED",t.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",t.ApplyCouponFailed="APPLY_COUPON_FAILED",t.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",t.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",t.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(st||(st={}));var ct=function(){function t(t){this._couponRequestSender=t}return t.prototype.applyCoupon=function(t,e){var n=this;return function(r){return d.Observable.create((function(o){var i=r.getState().checkout.getCheckout();if(!i)throw new b(v.MissingCheckout);o.next((0,u.createAction)(st.ApplyCouponRequested)),n._couponRequestSender.applyCoupon(i.id,t,e).then((function(t){var e=t.body;o.next((0,u.createAction)(st.ApplyCouponSucceeded,e)),o.complete()})).catch((function(t){o.error((0,u.createErrorAction)(st.ApplyCouponFailed,t))}))}))}},t.prototype.removeCoupon=function(t,e){var n=this;return function(r){return d.Observable.create((function(o){var i=r.getState().checkout.getCheckout();if(!i)throw new b(v.MissingCheckout);o.next((0,u.createAction)(st.RemoveCouponRequested)),n._couponRequestSender.removeCoupon(i.id,t,e).then((function(t){var e=t.body;o.next((0,u.createAction)(st.RemoveCouponSucceeded,e)),o.complete()})).catch((function(t){o.error((0,u.createErrorAction)(st.RemoveCouponFailed,t))}))}))}},t}();const ut=ct,lt=["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","customer.customerGroup","payments","promotions.banners"];var dt;function pt(t){return(0,l.uniq)(t).join(",")}!function(t){t.AvailableShippingOptions="consignments.availableShippingOptions",t.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",t.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(dt||(dt={}));var ht=function(){return ht=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===F()&&V().warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var c=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const kt=At;var Tt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const xt=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return Tt(e,t),e}(Error);var Dt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Mt=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Dt(e,t),e}(xt);var zt,Rt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(zt||(zt={}));const Nt=function(t){function e(e){var n=t.call(this,function(t){switch(t){case zt.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case zt.MissingCart:return"Unable to proceed because cart data is unavailable.";case zt.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case zt.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case zt.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case zt.MissingCheckoutConfig:case zt.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case zt.MissingOrder:return"Unable to proceed because order data is unavailable.";case zt.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case zt.MissingPayment:return"Unable to proceed because payment data is unavailable.";case zt.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case zt.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case zt.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return Rt(e,t),e}(xt);function Ft(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,l.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function Lt(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Bt,jt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Bt||(Bt={}));const Ut=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Bt.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Bt.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Bt.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Bt.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return jt(e,t),e}(xt);var qt,Gt,Vt,Ht,Wt,Yt,Kt={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(qt||(qt={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(Gt||(Gt={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(Vt||(Vt={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(Ht||(Ht={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(Wt||(Wt={})),function(t){t.C0001="C0001"}(Yt||(Yt={}));var Jt=function(){return Jt=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(f)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return qe(r,void 0,void 0,(function(){var r,o;return Ge(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=i.sent().body,t.completeMerchantValidation(r),[3,3];case 2:return o=i.sent(),this._onError(o),[3,3];case 3:return[2]}}))}))},t.onshippingcontactselected=function(e){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._handleShippingContactSelected(t,n,e)]}))}))},t.onshippingmethodselected=function(e){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._handleShippingMethodSelected(t,n,e)]}))}))},t.oncancel=function(){return qe(r,void 0,void 0,(function(){var t;return Ge(this,(function(n){switch(n.label){case 0:this._hasApplePaySession=!1,n.label=1;case 1:return n.trys.push([1,4,,5]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 2:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 3:return[2,n.sent()];case 4:return n.sent(),[2,this._onError(new Ne)];case 5:return[2]}}))}))},t.onpaymentauthorized=function(n){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return qe(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m,v,g;return Ge(this,(function(b){switch(b.label){case 0:o=this._transformContactToAddress(n.shippingContact),b.label=1;case 1:return b.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return b.sent(),[3,4];case 3:return i=b.sent(),t.abort(),this._hasApplePaySession=!1,[2,this._onError(i)];case 4:if(a=e.storeProfile.storeName,s=this._paymentIntegrationService.getState(),c=s.getCartOrThrow().currency.decimalPlaces,u=s.getCheckoutOrThrow(),l=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=u.consignments[0].availableShippingOptions,p=null==d?void 0:d.find((function(t){return t.id===l})),h=null==d?void 0:d.filter((function(t){return t.id!==l})),f=p?[{label:p.description,amount:"".concat(p.cost.toFixed(c)),detail:p.additionalDescription,identifier:p.id}]:[],h&&Ve(Ve([],h.filter((function(t){return t.isRecommended})),!0),h.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return f.push({label:t.description,amount:"".concat(t.cost.toFixed(c)),detail:t.additionalDescription,identifier:t.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:a,amount:"".concat(u.grandTotal.toFixed(c))},[]),[2];y=d.find((function(t){return t.isRecommended})),m=y?y.id:d[0].id,v=p?p.id:m,b.label=5;case 5:return b.trys.push([5,7,,8]),[4,this._updateShippingOption(v)];case 6:return b.sent(),[3,8];case 7:return g=b.sent(),[2,this._onError(g)];case 8:return s=this._paymentIntegrationService.getState(),u=s.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:f,newTotal:{type:"final",label:a,amount:"".concat(u.grandTotal.toFixed(c))},newLineItems:this._getUpdatedLineItems(u,c)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return qe(this,void 0,void 0,(function(){var r,o,i,a,s,c;return Ge(this,(function(u){switch(u.label){case 0:r=e.storeProfile.storeName,o=n.shippingMethod.identifier,u.label=1;case 1:return u.trys.push([1,3,,4]),[4,this._updateShippingOption(o)];case 2:return u.sent(),[3,4];case 3:return i=u.sent(),t.abort(),this._hasApplePaySession=!1,[2,this._onError(i)];case 4:return a=this._paymentIntegrationService.getState(),s=a.getCartOrThrow().currency.decimalPlaces,c=a.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:r,amount:"".concat(c.grandTotal.toFixed(s))},newLineItems:this._getUpdatedLineItems(c,s)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return qe(this,void 0,void 0,(function(){return Ge(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return qe(this,void 0,void 0,(function(){var n;return Ge(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return qe(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m,v;return Ge(this,(function(g){switch(g.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,s=o.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),l=u.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Fe.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:d=g.sent(),g.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},h=this._transformContactToAddress(a),f=this._transformContactToAddress(s),y=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",g.label=3;case 3:return g.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Ue(Ue({},h),{email:y,phone:m}))];case 4:return g.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(f)]:[3,6];case 5:g.sent(),g.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return g.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:return v=g.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),[2,this._onError(v)];case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return qe(this,void 0,void 0,(function(){return Ge(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return qe(this,void 0,void 0,(function(){var t,e;return Ge(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Fe.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Fe.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const We=He,Ye=ie((function(t){var e=t.getState().getHost;return new We((0,s.createRequestSender)({host:e()}),t,new Be,new Pe(new ze((0,c.getScriptLoader)(),window)))}),[{id:"applepay"}]);var Ke=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Je=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the client library of a payment method has thrown an unexpected error.")||this;return n.name="PaymentMethodFailedError",n.type="payment_method_client_invalid",n}return Ke(e,t),e}(xt);var Ze=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Xe={body:{},headers:{},status:0},Qe=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,s=e||Xe,c=s.body,u=s.headers,l=s.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=l,a.errors=i||[],a}return Ze(e,t),e}(xt);const $e=Qe;var tn=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const en=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return tn(e,t),e}($e);var nn=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},rn=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&u.lineItems.physicalItems.length>0?[4,this.paymentIntegrationService.updateBillingAddress(_[0])]:[3,9];case 8:A.sent(),A.label=9;case 9:return _.length>0&&u.lineItems.digitalItems.length>0&&0===u.lineItems.physicalItems.length?(I=C[0],P=I.firstName,O=I.lastName,E=$n($n({},_[0]),{firstName:P,lastName:O}),[4,this.paymentIntegrationService.updateBillingAddress(E)]):[3,11];case 10:A.sent(),A.label=11;case 11:return b.length>0&&u.lineItems.physicalItems.length>0?[4,this.paymentIntegrationService.updateShippingAddress(b[0])]:[3,14];case 12:return A.sent(),e&&p?[4,this.setShippingOption()]:[3,14];case 13:A.sent(),A.label=14;case 14:return[3,16];case 15:return A.sent(),[3,16];case 16:return[2]}}))}))},t.prototype.mapPayPalToBcInstrument=function(t,e){if(e)return e.map((function(e){var n=e.id,r=e.paymentSource.card,o=r.brand,i=r.expiry,a=r.lastDigits,s=i.split("-"),c=s[0];return{bigpayToken:n,brand:o,defaultInstrument:!1,expiryMonth:s[1],expiryYear:c,iin:"",last4:a,method:t,provider:t,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Qn.PAN}}))},t.prototype.mapPayPalToBcAddress=function(t,e){if(!t)return[];var n=this.paymentIntegrationService.getState().getCountries()||[];return t.map((function(t){return{id:Date.now(),type:"paypal-address",firstName:t.firstName||"",lastName:t.lastName||"",company:t.company||"",address1:t.streetAddress,address2:t.extendedAddress||"",city:t.locality,stateOrProvince:t.region,stateOrProvinceCode:t.region,country:(r=t.countryCodeAlpha2,o=n.find((function(t){return t.code===r})),(null==o?void 0:o.name)||""),countryCode:t.countryCodeAlpha2,postalCode:t.postalCode,phone:e&&e[0]||"",customFields:[]};var r,o}))},t.prototype.getPayPalBillingAddresses=function(t){var e=t||{},n=e.card,r=e.name;if(n){var o=n.paymentSource.card.billingAddress,i=o.firstName,a=o.lastName,s=r||{},c=s.firstName,u=s.lastName,d=(t||{}).shippingAddress,p=$n($n({},n.paymentSource.card.billingAddress),{firstName:i||c,lastName:a||u});return d&&(0,l.isEqual)(this.normalizeAddress(p),this.normalizeAddress(d))?d:p}},t.prototype.normalizeAddress=function(t){return(0,l.omit)(t,["id"])},t.prototype.mergeShippingAndBillingAddresses=function(t,e){var n=this,r=e.filter((function(e){return!t.some((function(t){return(0,l.isEqual)(n.normalizeAddress(t),n.normalizeAddress(e))}))}));return nr(nr([],t,!0),r,!0)},t.prototype.getMethodIdOrThrow=function(){if(!this.methodId)throw new Mt('Unable to proceed because "methodId" argument is not provided.');return this.methodId},t.prototype.setShippingOption=function(){var t;return tr(this,void 0,void 0,(function(){var e,n,r,o,i;return er(this,(function(a){switch(a.label){case 0:return e=this.paymentIntegrationService.getState(),n=e.getConsignments()||[],r=(null===(t=n[0])||void 0===t?void 0:t.availableShippingOptions)||[],(o=r.find((function(t){return t.isRecommended})))||r.length?(i=o||r[0],[4,this.paymentIntegrationService.selectShippingOption(i.id)]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2]}}))}))},t}();const or=rr,ir=ie((function(t){var e=window,n=new An(new ze((0,c.getScriptLoader)(),e),e),r=new Vn("paypalFastlane"),o=new or(t,n,r);return new Xn(t,o)}),[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var ar=function(){return ar=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),r=document.createElement("div");return r.style.display="flex",r.style.flexDirection="column",r.style.visibility="hidden",r.style.width="max-content",r.className=e,r.innerHTML=n,t.appendChild(r),r},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const lr=ur,dr=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new lr(t,(0,mn.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);var pr=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),hr=function(){return hr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}(),br=function(t,e){return!!t&&(!!t.lineItems.physicalItems.some((function(t){return t.isShippingRequired}))||!(!e||!t.lineItems.customItems)&&t.lineItems.customItems.length>0)};var wr,_r,Sr,Cr,Ir,Pr,Or,Er;function Ar(t){return t in Pr}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(wr||(wr={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(_r||(_r={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Sr||(Sr={})),function(t){t.pill="pill",t.rect="rect"}(Cr||(Cr={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ir||(Ir={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(Pr||(Pr={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(Or||(Or={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Er||(Er={}));var kr=function(){return kr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":D.length>0?D:void 0,commit:w,components:oi(oi(["buttons","hosted-fields","messages","payment-fields","legal"],z,!0),I,!0),currency:e,intent:a},f&&{"buyer-country":u}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=ei(ei({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const ai=ii,si=ie((function(t){return new Ur(t,new Yr(Xr(),new ti(t,new ai((0,c.getScriptLoader)())),(0,s.createRequestSender)(),(0,mn.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]);function ci(){var t,e=window.navigator;return t=e.language?e.language:e.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof e.javaEnabled&&e.javaEnabled(),language:t,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var ui=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),li=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},di=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const ki=Ai;var Ti="This API endpoint is for internal use only and may change in the future",xi=function(){return xi=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?z:void 0,"disable-funding":M.length>0?M:void 0,commit:w,components:Bi(Bi(["buttons","hosted-fields","payment-fields","legal"],x,!0),D,!0),currency:e,intent:a},f&&{"buyer-country":u}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Ni(Ni({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Ui=ji,qi=function(t){var e=t.getState().getHost;return new ki((0,mn.createFormPoster)(),t,new Ri((0,s.createRequestSender)({host:e()})),new Ui((0,c.getScriptLoader)()))};var Gi=function(){return Gi=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(s=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(i),[4,this.paymentIntegrationService.updateShippingAddress(s)]):[3,6];case 4:return u.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:u.sent(),u.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return u.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return u.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return c=u.sent(),this.handleError(c),[3,10];case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Vi(this,void 0,void 0,(function(){var e,n,r;return Hi(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:return r=o.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Vi(this,void 0,void 0,(function(){var e,n;return Hi(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const Yi=Wi,Ki=ie((function(t){return new Yi(t,qi(t))}),[{id:"paypalcommerce"}]);var Ji=function(){return Ji=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(s=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(i),[4,this.paymentIntegrationService.updateShippingAddress(s)]):[3,6];case 4:return u.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:u.sent(),u.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return u.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return u.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return c=u.sent(),this.handleError(c),[3,10];case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Zi(this,void 0,void 0,(function(){var e,n,r;return Xi(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:return r=o.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Zi(this,void 0,void 0,(function(){var e,n;return Xi(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const $i=Qi,ta=ie((function(t){return new $i(t,qi(t))}),[{id:"paypalcommercecredit"}]);var ea=function(){return ea=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?h:void 0,"disable-funding":f.length>0?f:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},c&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Nt(zt.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,s=n.buyerCountry;return{options:sa({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=sa(sa({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const da=la;function pa(){return new da((0,c.createScriptLoader)())}var ha,fa,ya,ma,va;!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(ha||(ha={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(fa||(fa={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(ya||(ya={})),function(t){t.pill="pill",t.rect="rect"}(ma||(ma={})),function(t){t.SUCCEEDED="succeeded",t.FAILED="failed",t.CANCELED="cancelled",t.UNRECOGNIZED="unrecognized"}(va||(va={}));var ga=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},ba=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this.paymentIntegrationService.updateShippingAddress(u)]:[3,6];case 4:return d=b.sent(),p=d.getPaymentMethodOrThrow(t),h=(p.initializationData||{}).isFastlaneShippingOptionAutoSelectEnabled,f=d.getConsignments()||[],y=(null===(n=f[0])||void 0===n?void 0:n.availableShippingOptions)||[],m=y[0],((v=y.find((function(t){return t.isRecommended})))||m)&&h?(g=(null==v?void 0:v.id)||m.id,[4,this.paymentIntegrationService.selectShippingOption(g)]):[3,6];case 5:b.sent(),b.label=6;case 6:return[2]}}))}))},t.prototype.getFastlaneStyles=function(t,e){var n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{},r=n.fastlaneStyles;return Oa(n.isFastlaneStylingEnabled?r:{},null==e?void 0:e.styles)},t}();const Ta=ka,xa=ie((function(t){return new Ta(t,pa(),Ca())}),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function Da(t){return"stripeLinkAuthenticationState"in t}function Ma(t){return"object"==typeof t&&null!==t&&"initializationData"in t&&void 0!==t.initializationData&&null!==t.initializationData&&"object"==typeof t.initializationData&&"stripePublishableKey"in t.initializationData&&"stripeConnectedAccount"in t.initializationData&&"shopperLanguage"in t.initializationData&&void 0!==t.initializationData.stripePublishableKey&&void 0!==t.initializationData.stripeConnectedAccount&&void 0!==t.initializationData.shopperLanguage}var za,Ra,Na,Fa,La,Ba;!function(t){t.SHIPPING="shipping",t.BILLING="billing"}(za||(za={})),function(t){t.SPLIT="split",t.FULL="full",t.ORGANIZATION="organization"}(Ra||(Ra={})),function(t){t.CreditCard="card",t.Link="link",t.SOFORT="sofort",t.EPS="eps",t.GRABPAY="grabpay",t.BANCONTACT="bancontact",t.IDEAL="ideal",t.GIROPAY="giropay",t.ALIPAY="alipay",t.KLARNA="klarna",t.OCS="stripe_ocs"}(Na||(Na={})),function(t){t.NEVER="never",t.AUTO="auto",t.ALWAYS="always",t.PAYMENT="payment",t.IF_REQUIRED="if_required"}(Fa||(Fa={})),function(t){t.PAYMENT="payment",t.AUTHENTICATION="linkAuthentication",t.SHIPPING="address"}(La||(La={})),function(t){t.REQUIRES_PAYMENT_METHOD="requires_payment_method",t.REQUIRES_CONFIRMATION="requires_confirmation",t.REQUIRES_ACTION="requires_action",t.PROCESSING="processing",t.SUCCEEDED="succeeded",t.CANCELED="canceled"}(Ba||(Ba={}));var ja=function(){function t(t,e){this.paymentIntegrationService=t,this.scriptLoader=e}return t.prototype.initialize=function(t){var e,n,r,o,i;return n=this,r=void 0,i=function(){var n,r,o,i,a,s,c,u,l,d,p,h,f,y,m,v,g,b,w,_,S,C,I,P,O,E,A,k,T,x=this;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new nt(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,s="/api/storefront/checkout/".concat(t),c=as({Accept:E.JsonV1},A);return this._requestSender.put(s,{params:{include:is(lt,i)},body:e,headers:c,timeout:a})},t}();const cs=ss;var us;!function(t){t.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",t.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",t.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",t.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",t.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",t.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}(us||(us={}));var ls=function(){return ls=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadFormFields",null),t}();const ys=fs;var ms=function(){return ms=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadPaymentMethod",null),t}();const Cs=Ss;var Is=function(){return Is=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&js(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleMessage",null),t}();const Hs=Vs;var Ws=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Ys=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return Ws(e,t),e}(m);var Ks=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Js=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return Ks(e,t),e}(m);var Zs=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Xs=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return Zs(e,t),e}(m);var Qs=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},$s=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!s?a:"".concat(a," ").concat("/"," ").concat(s)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const hu=pu,fu=require("card-validator"),yu=function(){function t(){}return t.prototype.format=function(t){var e=(0,fu.number)(t).card;if(!e)return t;var n=(0,l.max)((0,fu.creditCardType)(t).map((function(t){return(0,l.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,fu.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();var mu=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new b(v.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,l.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"==typeof t&&"address"in t},t}();const Bu=Lu;var ju=function(){return ju=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),r=document.createElement("div");return r.style.display="flex",r.style.flexDirection="column",r.style.visibility="hidden",r.className=e,r.innerHTML=n,t.appendChild(r),r},t}();const Kl=Yl;var Jl=function(){function t(t,e){this._store=t,this._customerActionCreator=e}return t.prototype.signIn=function(t,e){return this._store.dispatch(this._customerActionCreator.signInCustomer(t,e))},t.prototype.signOut=function(t){return this._store.dispatch(this._customerActionCreator.signOutCustomer(t))},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t}();const Zl=Jl;function Xl(t){return"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat(t)}var Ql={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function $l(t){var e=t.replace("-","_").toLowerCase().split("_"),n=e[0],r=e[1],o="".concat(n,"_").concat(r),i=Ql[n];return i?i.indexOf(o)>-1?o:i[0]:"en_us"}var td=function(){function t(t,e,n,r,o){this._store=t,this._paymentMethodActionCreator=e,this._remoteCheckoutActionCreator=n,this._masterpassScriptLoader=r,this._locale=o}return t.prototype.initialize=function(t){var e=this,n=t.masterpass,r=t.methodId;if(!n||!r)throw new Pt('Unable to proceed because "options.masterpass" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(t){if(e._paymentMethod=t.paymentMethods.getPaymentMethod(r),!e._paymentMethod||!e._paymentMethod.initializationData.checkoutId)throw new b(v.MissingPaymentMethod);var o=t.cart.getCart();if(!o)throw new b(v.MissingCart);var i=n.container,a={checkoutId:e._paymentMethod.initializationData.checkoutId,allowedCardTypes:e._paymentMethod.initializationData.allowedCardTypes,amount:o.cartAmount.toString(),currency:o.currency.code,cartId:o.id,suppressShippingAddress:!1,callbackUrl:Xl("checkout")},s={useMasterpassSrc:e._paymentMethod.initializationData.isMasterpassSrcEnabled,language:$l(e._locale),testMode:e._paymentMethod.config.testMode,checkoutId:e._paymentMethod.initializationData.checkoutId};return e._masterpassScriptLoader.load(s).then((function(t){e._signInButton=e._createSignInButton(i),e._signInButton.addEventListener("click",(function(){t.checkout(a)}))}))})).then((function(){return e._store.getState()}))},t.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._signInButton&&this._signInButton.parentNode&&(this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve(this._store.getState())},t.prototype.signIn=function(){throw new Wl('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},t.prototype.signOut=function(t){var e=this._store.getState().payment.getPaymentId();return e?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e.providerId,t)):Promise.resolve(this._store.getState())},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t.prototype._createSignInButton=function(t){var e=document.querySelector("#".concat(t));if(!this._paymentMethod||!this._paymentMethod.initializationData.checkoutId)throw new b(v.MissingPaymentMethod);if(!e)throw new Pt("Unable to create sign-in button without valid container ID.");var n=document.createElement("input");if(n.type="image",this._paymentMethod.initializationData.isMasterpassSrcEnabled){var r=this._paymentMethod.config.testMode?"sandbox.":"",o=this._paymentMethod.initializationData.checkoutId,i=["locale=".concat($l(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(o)];n.src=["https://".concat(r,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),i.join("&")].join("?")}else n.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(n),n},t}();const ed=td;var nd=function(){function t(t,e){this._store=t,this._remoteCheckoutActionCreator=e}return t.prototype.signIn=function(){throw new Wl('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},t.prototype.signOut=function(t){var e=this._store.getState().payment.getPaymentId();return e?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e.providerId,t)):Promise.resolve(this._store.getState())},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t}();const rd=nd;var od,id,ad=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),sd=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to no extension configured for this region.")||this;return n.name="ExtensionNotFoundError",n.type="extension_not_found",n}return ad(e,t),e}(m);function cd(t){var e,n=null===(e=document.querySelector('[data-extension-id="'.concat(t.id,'"]')))||void 0===e?void 0:e.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new sd("Unable to post due to no extension rendered for ID: ".concat(t.id,"."));return new qs(t.url,n.contentWindow)}function ud(t,e){return(0,n(483).iframeResizer)(t,e)}!function(t){t.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",t.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",t.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",t.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",t.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",t.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(od||(od={})),function(t){t.ExtensionReady="EXTENSION:READY",t.ExtensionFailed="EXTENSION:FAILED"}(id||(id={}));var ld,dd=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),pd=function(t){function e(e){var n=t.call(this,e||"Unable to load an extension")||this;return n.name="ExtensionNotLoadedError",n.type="extension_not_loaded",n}return dd(e,t),e}(m);!function(t){t.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",t.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",t.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(ld||(ld={}));var hd=function(){function t(t){this._options=t}return t.prototype.createFrame=function(t,e,n,r){var o=document.getElementById(e),i=(this._options||{}).timeout,a=void 0===i?6e4:i;if(!o)throw new pd("Unable to embed the iframe because the container element could not be found.");var s=document.createElement("iframe");return s.src=t,s.style.border="none",s.style.display="none",s.style.width="100%",o.appendChild(s),this._toResizableFrame(s,a,n,r).catch((function(t){throw o.removeChild(s),t}))},t.prototype._toResizableFrame=function(t,e,n,r){return o=this,i=void 0,s=function(){var o,i;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&(n[e.code]={discount_amount:t.toInteger(e.discountedAmount),discount_display_name:e.displayName})})),e.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:t.toInteger(e.discountAmount),discount_display_name:"discount"}),n},t.prototype.getCategories=function(t){return t?t.map((function(t){return t.map((function(t){return t.name}))})):[[]]},t}();const ip=op;var ap;!function(t){t.PROD="//cdn1.affirm.com/js/v2/affirm.js",t.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(ap||(ap={}));const sp=function(){function t(t){void 0===t&&(t=window),this.affirmWindow=t}return t.prototype.load=function(t,e){void 0===t&&(t="");var n=e?ap.SANDBOX:ap.PROD;if(function(t,e,n,r,o,i,a){var s=t[n]||{},c=document.createElement(i),u=document.getElementsByTagName(i)[0],l=function(t,e,n){return function(){t[e]._.push([n,arguments])}};s[r]=l(s,r,"set");var d=s[r];s[o]={},s[o]._=[],d._=[],s._=[],s[o][a]=l(s,o,a),s.jsReady=function(){s._.push([a,arguments])};for(var p=0,h="set add save post open empty reset on off trigger ready setProduct".split(" ");p0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,h=o.getCheckoutOrThrow().outstandingBalance;return{paymentType:t,amount:h,fallback:{url:"url-placeholder",buttonText:"button placeholder"},currencyCode:l.code,shippingAddressRequired:p,email:d,givenName:s,surname:c,address:{countryCode:u},onPaymentStart:function(o,i){return tf(r,void 0,void 0,(function(){var r,a,s,c;return ef(this,(function(u){switch(u.label){case 0:return this.isLPMsUpdateExperimentEnabled?[4,this.getLPMsBasicPaymentData()]:(this.orderId=o.paymentId,i(),[2]);case 1:r=u.sent(),a=$h($h({},r),{formattedPayload:(c={method:t},c["".concat(t,"_account")]={order_id:o.paymentId},c)}),u.label=2;case 2:return u.trys.push([2,5,,6]),[4,this.paymentIntegrationService.submitOrder(e,n)];case 3:return u.sent(),[4,this.paymentIntegrationService.submitPayment({methodId:t,paymentData:a})];case 4:return u.sent(),[3,6];case 5:if(s=u.sent(),this.isBraintreeOrderSavedResponse(s)&&s.body.additional_action_required.data.order_id_saved_successfully)return i(),[2];throw s;case 6:return[2]}}))}))}}},t.prototype.getInstantLPMCallback=function(t,e,n,r,o){var i=this,a=this.paymentIntegrationService.getState().getCartOrThrow();return function(s,c){return tf(i,void 0,void 0,(function(){var i,u,l,d;return ef(this,(function(p){switch(p.label){case 0:return s?"LOCAL_PAYMENT_WINDOW_CLOSED"===s.code?(this.toggleLoadingIndicator(!1),[2,e()]):(this.toggleLoadingIndicator(!1),[2,e(new en)]):[4,this.getLPMsBasicPaymentData()];case 1:i=p.sent(),u=$h($h({},i),{formattedPayload:(d={method:n},d["".concat(n,"_account")]=$h({email:a.email,token:c.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId}),d)}),p.label=2;case 2:return p.trys.push([2,6,,7]),this.isLPMsUpdateExperimentEnabled?[3,4]:[4,this.paymentIntegrationService.submitOrder(r,o)];case 3:p.sent(),p.label=4;case 4:return[4,this.paymentIntegrationService.submitPayment({methodId:n,paymentData:u})];case 5:return p.sent(),[2,t(void 0)];case 6:return l=p.sent(),this.handleError(l),[2,e(l)];case 7:return[2]}}))}))}},t.prototype.toggleLoadingIndicator=function(t){t&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},t.prototype.handleError=function(t){var e=(this.braintreelocalmethods||{}).onError;this.toggleLoadingIndicator(!1),e&&"function"==typeof e&&e(t)},t.prototype.isNonInstantPaymentMethod=function(t){return t.toUpperCase()in be},t.prototype.isBraintreeRedirectError=function(t){var e;if("object"!=typeof t||null===t)return!1;var n=t.body;return!!n&&!!(null===(e=n.additional_action_required)||void 0===e?void 0:e.data.redirect_url)},t.prototype.isBraintreeOrderSavedResponse=function(t){var e;if("object"!=typeof t||null===t)return!1;var n=t.body;return!!n&&(null===(e=n.additional_action_required)||void 0===e?void 0:e.data.hasOwnProperty("order_id_saved_successfully"))},t}();const rf=nf,of=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new rf(t,n,new Gh({styles:{backgroundColor:"black"}}))}),[{gateway:"braintreelocalmethods"}]);function af(t){return!!t&&("authenticationState"in t||"addresses"in t||"instruments"in t)}var sf=function(){return sf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this.paymentIntegrationService.updatePaymentProviderCustomer(sf(sf({},a),{instruments:lf([],s,!0)}))]:[3,3]):[3,3];case 2:return c.sent(),[2,s[0]];case 3:return[2,void 0]}}))}))},t}();const pf=df,hf=ie((function(t){var e=window,n=new An(new ze((0,c.getScriptLoader)(),e),e),r=new Vn("paypalFastlane"),o=new or(t,n,r);return new pf(t,o,r)}),[{id:"braintreeacceleratedcheckout"}]);var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?i(new Je(t.ErrorDescription)):t.Payment&&t.Payment.ExtendedData&&t.Payment.ExtendedData.SignatureVerification===by.Yes?o({token:e}):i(new Je("Transaction signature could not be validated."));case yy.Failure:return i(new Je("User failed authentication or an error was encountered while processing the transaction."));case yy.Error:return i(new Je(t.ErrorDescription))}}));var a={AcsUrl:t.acs_url,Payload:t.merchant_data},s=n._mapToPartialOrder(e,t.payer_auth_request);r.continue(gy.CCA,a,s)}))}))},t.prototype._mapToPartialOrder=function(t,e){var n={BillingAddress:this._mapToCardinalAddress(t.billingAddress)};return t.paymentData&&(n.Account=this._mapToCardinalAccount(t.paymentData)),t.billingAddress.email&&(n.Email1=t.billingAddress.email),t.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(t.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:t.id,Amount:t.amount,CurrencyCode:t.currencyCode,OrderChannel:"S",TransactionId:e}}},t.prototype._mapToCardinalAccount=function(t){return{AccountNumber:Number(t.ccNumber),ExpirationMonth:Number(t.ccExpiry.month),ExpirationYear:Number(t.ccExpiry.year),NameOnAccount:t.ccName,CardCode:Number(t.ccCvv)}},t.prototype._mapToCardinalAddress=function(t){var e={FirstName:t.firstName,LastName:t.lastName,Address1:t.address1,City:t.city,State:t.stateOrProvince,PostalCode:t.postalCode,CountryCode:t.countryCode};return t.address2&&(e.Address2=t.address2),t.phone&&(e.Phone1=t.phone),e},t.prototype._getClientSDK=function(){if(!this._sdk)throw new Ut(Bt.PaymentNotInitialized);return this._sdk},t}();const Sy=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(t,e){var n=this,r=e?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript("".concat(r,"?v=").concat(t)).then((function(){if(!n._window.Cardinal)throw new ee;return n._window.Cardinal}))},t}();var Cy=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Iy=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},Py=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0){var i=this.getInitializeOptions().containerId;if(i){var a=document.getElementById(i);if(a){var s=document.createElement("p");s.setAttribute("id","".concat(n,"-").concat(e,"-paragraph")),t.unsupportedMethodMessage&&(s.innerText=t.unsupportedMethodMessage,a.appendChild(s),t.disableButton(!0))}}}}},t}();const gv=vv;var bv=function(){function t(t,e){void 0===e&&(e=window),this.scriptLoader=t,this.mollieHostWindow=e}return t.prototype.load=function(t,e,n){return r=this,o=void 0,a=function(){return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?i:o[0]}var Ab=function(){return Ab=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?i(new Je(t.ErrorDescription)):t.Payment&&t.Payment.ExtendedData&&t.Payment.ExtendedData.SignatureVerification===M_.Yes?o({token:e}):i(new Je("Transaction signature could not be validated."));case k_.Failure:return i(new Je("User failed authentication or an error was encountered while processing the transaction."));case k_.Error:return i(new Je(t.ErrorDescription))}}));var a={AcsUrl:t.acs_url,Payload:t.merchant_data},s=n._mapToPartialOrder(e,t.payer_auth_request);r.continue(D_.CCA,a,s)}))}))},t.prototype._mapToPartialOrder=function(t,e){var n={BillingAddress:this._mapToCardinalAddress(t.billingAddress)};return t.paymentData&&(n.Account=this._mapToCardinalAccount(t.paymentData)),t.billingAddress.email&&(n.Email1=t.billingAddress.email),t.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(t.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:t.id,Amount:t.amount,CurrencyCode:t.currencyCode,OrderChannel:"S",TransactionId:e}}},t.prototype._mapToCardinalAccount=function(t){return{AccountNumber:Number(t.ccNumber),ExpirationMonth:Number(t.ccExpiry.month),ExpirationYear:Number(t.ccExpiry.year),NameOnAccount:t.ccName,CardCode:Number(t.ccCvv)}},t.prototype._mapToCardinalAddress=function(t){var e={FirstName:t.firstName,LastName:t.lastName,Address1:t.address1,City:t.city,State:t.stateOrProvince,PostalCode:t.postalCode,CountryCode:t.countryCode};return t.address2&&(e.Address2=t.address2),t.phone&&(e.Phone1=t.phone),e},t.prototype._getClientSDK=function(){if(!this._sdk)throw new oc(nc.PaymentNotInitialized);return this._sdk},t}();var N_=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(t,e){var n=this,r=e?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript("".concat(r,"?v=").concat(t)).then((function(){if(!n._window.Cardinal)throw new Ul;return n._window.Cardinal}))},t}();const F_=N_;var L_=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const B_=function(t){function e(e){var n=t.call(this,e||"The selected payment method was declined. Please select another payment method.")||this;return n.name="PaymentMethodDeclinedError",n.type="payment_declined",n}return L_(e,t),e}(m);var j_="ACKNOWLEDGE",U_="FINALIZE",q_=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),G_=function(){return G_=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleWalletButtonClick",null),t}();var tS;function eS(t){var e;return!!(null===(e=t.initializationData)||void 0===e?void 0:e.widgetConfig)}!function(t){t.FORM_POST="FormPost",t.WAIT_FOR_CUSTOMER="WaitForCustomer"}(tS||(tS={}));var nS,rS=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t.InvalidCart="invalid_cart"}(nS||(nS={}));const oS=function(t){function e(e,n){var r=t.call(this,function(t,e){return t===nS.InvalidCart?"Cart price is different to ".concat(e," plan amount."):"There was an error while processing your payment. Please try again or contact us."}(e,n))||this;return r.name="OpyError",r.type="opy_error",r.subtype=e,r}return rS(e,t),e}(m);var iS=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},aS=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0},t.prototype.setCompleted=function(t){var e=this.getCompletedPayments();e.push(t),this.setCompletedPayments(e)},t.prototype.getCompletedPayments=function(){return this._browserStorage.getItem(ES)||[]},t.prototype.setCompletedPayments=function(t){this._browserStorage.setItem(ES,t)},t}(),kS=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},TS=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]Date.now()}((e=new Date(t.vaultAccessExpiry),(n=new Date(e.getTime())).setMinutes(e.getMinutes()+2),n));var e,n},t.prototype._getCurrentAccessToken=function(t){var e=t.getState().instruments.getInstrumentsMeta();if(e)return{vaultAccessToken:e.vaultAccessToken,vaultAccessExpiry:e.vaultAccessExpiry}},t.prototype._getValidAccessToken=function(t){return t&&this._isValidVaultAccessToken(t)?Promise.resolve(t):this._instrumentRequestSender.getVaultAccessToken().then((function(t){return t.body}))},t.prototype._getShippingAddress=function(t){var e=t.getState(),n=e.shippingAddress.getShippingAddresses();return n.length>1?n:e.shippingAddress.getShippingAddress()},t.prototype._getSessionContext=function(t){var e=t.getState(),n=e.config.getStoreConfig(),r=e.cart.getCart();if(!n)throw new b(v.MissingCheckoutConfig);if(!r)throw new b(v.MissingCart);return{customerId:r.customerId,storeId:n.storeProfile.storeId,currencyCode:(n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency).code}},t}();const ZS=JS;var XS=function(){return XS=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(I))]:[3,10];case 9:k.sent(),k.label=10;case 10:return[2]}}))}))},t.prototype._getPayPalBillingAddress=function(t){var e=t.name,n=t.card.paymentSource.card.billingAddress;return _C(_C({},n),{firstName:n.firstName||(null==e?void 0:e.firstName),lastName:n.lastName||(null==e?void 0:e.lastName)})},t.prototype._getCountryNameByCountryCode=function(t,e){var n=e.find((function(e){return e.code===t}));return(null==n?void 0:n.name)||""},t.prototype._mapPayPalToBcAddress=function(t,e,n,r){return{id:Number(Date.now()),type:"paypal-address",firstName:t.firstName||"",lastName:t.lastName||"",company:t.company||"",address1:t.streetAddress,address2:t.extendedAddress||"",city:t.locality,stateOrProvince:t.region,stateOrProvinceCode:t.region,country:this._getCountryNameByCountryCode(t.countryCodeAlpha2,e),countryCode:t.countryCodeAlpha2,postalCode:t.postalCode,phone:n||"",customFields:r||[]}},t.prototype._normalizeAddress=function(t){return(0,l.omit)(t,["id"])},t.prototype._mergeShippingAndBillingAddresses=function(t,e){return(0,l.isEqual)(this._normalizeAddress(t),this._normalizeAddress(e))?[t]:[t,e]},t.prototype._mapPayPalToBcInstrument=function(t,e){if(e){var n=e.id,r=e.paymentSource.card,o=r.brand,i=r.expiry,a=r.lastDigits,s=i.split("-"),c=s[0];return{bigpayToken:n,brand:o,defaultInstrument:!1,expiryMonth:s[1],expiryYear:c,iin:"",last4:a,method:t,provider:t,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:wC.CVV,type:"card"}}},t.prototype._handleBraintreeFastlaneShippingAddressChange=function(){return SC(this,void 0,void 0,(function(){var t,e,n,r,o,i,a,s,c,u,l;return CC(this,(function(d){switch(d.label){case 0:return t=this._store.getState(),e=t.countries.getCountries()||[],[4,this._braintreeIntegrationService.getBraintreeFastlane()];case 1:return[4,d.sent().profile.showShippingAddressSelector()];case 2:return n=d.sent(),r=n.selectionChanged,o=n.selectedAddress,r?(i=this._store.getState(),a=i.shippingAddress.getShippingAddressesOrThrow(),s=i.paymentProviderCustomer.getPaymentProviderCustomer(),c=af(s)?s:{},(u=this._mapPayPalToBcAddress(o,e,o.phoneNumber,a[0].customFields))?(l=this._filterAddresses(IC([u],c.addresses||[],!0)),[4,this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(_C(_C({},c),{addresses:l})))]):[3,5]):[3,5];case 3:return d.sent(),[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(u))];case 4:return d.sent(),[2,u];case 5:return[2,void 0]}}))}))},t.prototype._filterAddresses=function(t){var e=this;return t.reduce((function(t,n){return n?t.some((function(t){return e._isEqualAddresses(t,n)}))?t:IC(IC([],t,!0),[n],!1):t}),[])},t.prototype._isEqualAddresses=function(t,e){return(0,l.isEqual)(this._normalizeAddress(t),this._normalizeAddress(e))},t.prototype._shouldUseBraintreeFastlaneShippingComponent=function(t){var e;return SC(this,void 0,void 0,(function(){var n,r,o,i;return CC(this,(function(a){switch(a.label){case 0:return n=this._store.getState(),r=n.paymentProviderCustomer.getPaymentProviderCustomer(),(o=af(r)?r:{})&&o!==me.CANCELED?[4,this._getBraintreePaymentMethodOrThrow(t)]:[3,2];case 1:return i=a.sent(),[2,!!(null===(e=null==i?void 0:i.initializationData)||void 0===e?void 0:e.isFastlaneEnabled)];case 2:return[2,!1]}}))}))},t.prototype._getBraintreePaymentMethodOrThrow=function(t){return SC(this,void 0,void 0,(function(){var e,n;return CC(this,(function(r){switch(r.label){case 0:return e=this._store.getState(),(n=e.paymentMethods.getPaymentMethod(t))?[3,2]:[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t))];case 1:return[2,r.sent().paymentMethods.getPaymentMethodOrThrow(t)];case 2:return[2,n]}}))}))},t}();const OC=PC,EC=function(){function t(t,e){this._store=t,this._consignmentActionCreator=e}return t.prototype.updateAddress=function(t,e){return this._store.dispatch(this._consignmentActionCreator.updateAddress(t,e))},t.prototype.selectOption=function(t,e){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(t,e))},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t}();var AC=function(){return AC=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(f))]:[3,7];case 6:v.sent(),v.label=7;case 7:return[2]}}))}))},t.prototype._handlePayPalShippingAddressChange=function(){return kC(this,void 0,void 0,(function(){var t,e,n,r,o,i,a,s,c;return TC(this,(function(u){switch(u.label){case 0:return[4,this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow().profile.showShippingAddressSelector()];case 1:return t=u.sent(),e=t.selectionChanged,n=t.selectedAddress,e?(r=this._store.getState(),o=r.shippingAddress.getShippingAddressesOrThrow(),i=r.paymentProviderCustomer.getPaymentProviderCustomer(),a=Pg(i)?i:{},s=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(n.address,n.name,n.phoneNumber,o[0].customFields),c=this._paypalCommerceFastlaneUtils.filterAddresses(function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const ZC=JC,XC=require("reselect");var QC=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0}})),J=tI(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===j_||t()===U_}})),(0,H.memoizeOne)((function(t,e){return{getPaymentId:B({checkout:t,order:e}),getPaymentIdOrThrow:j({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:q({checkout:t,order:e}),getPaymentToken:G({checkout:t,order:e}),getPaymentTokenOrThrow:V({checkout:t,order:e}),getPaymentRedirectUrl:W({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:Y({checkout:t,order:e}),isPaymentDataRequired:K({checkout:t,order:e}),isPaymentDataSubmitted:J({checkout:t,order:e})}}))),Ct=function(){var t=tI((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=tI((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,H.memoizeOne)((function(n){return void 0===n&&(n=aE),{getApplyError:t(n),isApplying:e(n)}}))}(),It=function(){var t=tI((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=tI((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,H.memoizeOne)((function(n){return void 0===n&&(n=GO),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Pt=(Z=tI((function(t){return t.data}),(function(t){return function(){return t}})),X=tI((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),Q=tI((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,H.memoizeOne)((function(t){return void 0===t&&(t=zO),{getEmail:Z(t),getSendError:X(t),isSending:Q(t)}}))),Ot=function(){var t=tI((function(t){return t.data}),(function(t){return function(){return t}})),e=tI((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=tI((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=tI((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,H.memoizeOne)((function(o){return void 0===o&&(o=fP),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n,r=$(t.billingAddress),o=tt(t.cart),i=et(t.checkoutButton),a=rt(t.countries),s=ot(t.coupons),c=it(t.customer),u=at(t.customerStrategies),l=Ot(t.extensions),d=ut(t.formFields),p=st(t.giftCertificates),h=ct(t.instruments),f=_t(t.orderBillingAddress),y=lt(t.paymentMethods),m=ht(t.paymentProviderCustomer),v=dt(t.paymentStrategies),g=pt(t.pickupOptions),b=ft(t.remoteCheckout),w=yt(t.consignments),_=mt(t.shippingCountries),S=vt(t.shippingStrategies),C=It(t.subscriptions),I=Ct(t.storeCredit),P=Pt(t.signInEmail),O=gt(t.consignments,o),E=bt(t.checkout,r,o,O,s,c,p),A=wt(t.order,f,s),k=St(E,A),T={billingAddress:r,cart:o,checkout:E,checkoutButton:i,config:nt(t.config,t.formFields),consignments:O,countries:a,coupons:s,customer:c,customerStrategies:u,extensions:l,form:d,giftCertificates:p,instruments:h,order:A,orderBillingAddress:f,payment:k,paymentMethods:y,paymentProviderCustomer:m,paymentStrategies:v,pickupOptions:g,remoteCheckout:b,shippingAddress:w,shippingCountries:_,shippingStrategies:S,signInEmail:P,subscriptions:C,storeCredit:I};return e.shouldWarnMutation?(n=T,Object.keys(n).reduce((function(t,e){return t[e]=tE(n[e]),t}),{})):T}}var uE=function(){return uE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([bE],t)}();const _E=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([bE],t)}();function SE(t){return{errors:new wE(t),statuses:new _E(t)}}var CE=function(){return CE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const PE=IE;var OE=function(){return OE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n55?55:t<25?25:t}function ME(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,s=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function zE(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var RE=function(){return RE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleWalletButtonClick",null),t}();var XE=function(){return XE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(f)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return fA(r,void 0,void 0,(function(){var r;return yA(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return fA(r,void 0,void 0,(function(){return yA(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return fA(r,void 0,void 0,(function(){var t;return yA(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Ne;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return fA(this,void 0,void 0,(function(){var n,r;return yA(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Nt(zt.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new mi;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Nt(zt.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return fA(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y;return yA(this,(function(m){switch(m.label){case 0:o=this._transformContactToAddress(n.shippingContact),m.label=1;case 1:return m.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return m.sent(),[3,4];case 3:throw m.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,s=i.getCheckoutOrThrow(),c=null===(r=s.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,u=s.consignments[0].availableShippingOptions,l=null==u?void 0:u.find((function(t){return t.id===c})),d=null==u?void 0:u.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:"".concat(l.cost.toFixed(a)),detail:l.additionalDescription,identifier:l.id}]:[],d&&mA(mA([],d.filter((function(t){return t.isRecommended})),!0),d.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(u instanceof Array))throw new Error("Shipping options not available.");if(0===u.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(s.grandTotal.toFixed(a))},[]),[2];h=u.find((function(t){return t.isRecommended})),f=h?h.id:u[0].id,y=l?l.id:f,m.label=5;case 5:return m.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return m.sent(),[3,8];case 7:throw m.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),s=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(s.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(s,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return fA(this,void 0,void 0,(function(){var r,o,i,a;return yA(this,(function(s){switch(s.label){case 0:r=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return s.sent(),[3,4];case 3:throw s.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return fA(this,void 0,void 0,(function(){return yA(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return fA(this,void 0,void 0,(function(){var n;return yA(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return fA(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m;return yA(this,(function(v){switch(v.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,s=o.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),l=u.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Fe.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:d=v.sent(),v.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},h=this._transformContactToAddress(a),f=this._transformContactToAddress(s),y=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",v.label=3;case 3:return v.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(hA(hA({},h),{email:y,phone:m}))];case 4:return v.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(f)]:[3,6];case 5:v.sent(),v.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return v.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return v.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw v.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return fA(this,void 0,void 0,(function(){return yA(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return fA(this,void 0,void 0,(function(){var t,e;return yA(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Fe.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Fe.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const gA=vA,bA=ie((function(t){var e=t.getState().getHost;return new gA((0,s.createRequestSender)({host:e()}),t,new Be,new Pe(new ze((0,c.getScriptLoader)(),window)))}),[{id:"applepay"}]);var wA=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,s,c,u,l,d,p,h;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const EA=OA,AA=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new EA(t,(0,mn.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function kA(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,s=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function TA(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var xA=function(){return xA=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(u=l.sent()))throw new Error(u);throw u;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return ek(this,void 0,void 0,(function(){var e,n,r;return nk(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return ek(this,void 0,void 0,(function(){var e,n;return nk(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const ok=rk,ik=ie((function(t){return new ok(t,qi(t))}),[{id:"paypalcommerce"}]);var ak=function(){return ak=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(u=l.sent()))throw new Error(u);throw u;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return sk(this,void 0,void 0,(function(){var e,n,r;return ck(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return sk(this,void 0,void 0,(function(){var e,n;return ck(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?Wv(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const lk=uk,dk=ie((function(t){return new lk(t,qi(t),pa())}),[{id:"paypalcommercecredit"}]);var pk=function(){return pk=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]6e5)&&t instanceof Vk&&t.subtype===qk.MissingContent?(this._storage.removeItem(Yk),this._storage.removeItem(Wk),this._allowCookie()):Promise.reject()},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const Jk=Kk;var Zk=function(){function t(t){this._options=t}return t.prototype.createFrame=function(t,e){var n=document.getElementById(e),r=(this._options||{}).timeout,o=void 0===r?6e4:r;if(!n)throw new Vk("Unable to embed the iframe because the container element could not be found.",qk.MissingContainer);var i=document.createElement("iframe");return i.src=t,i.style.border="none",i.style.display="none",i.style.width="100%",i.allowPaymentRequest=!0,i.allow="payment",n.appendChild(i),this._toResizableFrame(i,o).catch((function(t){throw n.removeChild(i),t}))},t.prototype._toResizableFrame=function(t,e){return new Promise((function(n,r){var o=window.setTimeout((function(){r(new Vk("Unable to embed the iframe because the content could not be loaded."))}),e),i=function(e){if((e.origin===Bs(t.src).origin||e.origin===Gs(Bs(t.src)).origin)&&(js(e.data,Bk.FrameError)&&(a(),r(new Vk(e.data.payload.message,qk.MissingContent))),js(e.data,Bk.FrameLoaded))){t.style.display="";var o=ud({scrolling:!1,sizeWidth:!1,heightCalculationMethod:e.data.payload&&e.data.payload.contentId?"taggedElement":"lowestElement"},t);a(),n(o[o.length-1])}},a=function(){window.removeEventListener("message",i),window.clearTimeout(o)};window.addEventListener("message",i)}))},t}();const Xk=Zk;var Qk="BigCommerce.EmbeddedCheckout";function $k(t){var e=Bs(t.url).origin;return new Jk(new Xk,new Hs(e),new qs(e),new Gh({styles:t.styles&&t.styles.loadingIndicator}),(0,s.createRequestSender)(),new Cw(Qk),window.location,t).attach()}function tT(t){if(t.payload&&t.payload.contentId){var e=document.getElementById(t.payload.contentId);e&&!e.hasAttribute("data-iframe-height")&&e.setAttribute("data-iframe-height","")}}function eT(t){return"object"==typeof t&&null!==t&&"message"in t&&"type"in t}var nT=function(){function t(t,e,n,r){void 0===r&&(r={}),this._messageListener=t,this._messagePoster=e,this._untargetedMessagePoster=n,this._messageHandlers=r,this._messageListener.listen()}return t.prototype.postComplete=function(){var t={type:Bk.CheckoutComplete};this._postMessage(t)},t.prototype.postError=function(t){var e={type:Bk.CheckoutError,payload:this._transformError(t)};this._postMessage(e)},t.prototype.postFrameError=function(t){var e={type:Bk.FrameError,payload:this._transformError(t)};this._postMessage(e,{untargeted:!0})},t.prototype.postFrameLoaded=function(t){var e={type:Bk.FrameLoaded,payload:t};this._postMessage(e)},t.prototype.postLoaded=function(){var t={type:Bk.CheckoutLoaded};this._postMessage(t)},t.prototype.postSignedOut=function(){var t={type:Bk.SignedOut};this._postMessage(t)},t.prototype.receiveStyles=function(t){this._messageListener.addListener(Hk.StyleConfigured,(function(e){var n=e.payload;t(n)}))},t.prototype._postMessage=function(t,e){if(this._notifyMessageHandlers(t),e&&e.untargeted)return this._untargetedMessagePoster.post(t);this._messagePoster.post(t)},t.prototype._notifyMessageHandlers=function(t){var e=this;Object.keys(this._messageHandlers).forEach((function(n){if(t.type===n){var r=e._messageHandlers[n];r&&r.call(null,t)}}))},t.prototype._transformError=function(t){return{message:t.message,type:eT(t)?t.type:void 0,subtype:eT(t)?t.subtype:void 0}},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const rT=nT;const oT=function(){function t(){}return t.prototype.postComplete=function(){},t.prototype.postError=function(){},t.prototype.postFrameError=function(){},t.prototype.postFrameLoaded=function(){},t.prototype.postLoaded=function(){},t.prototype.postSignedOut=function(){},t.prototype.receiveStyles=function(){},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();function iT(t){var e;n(405);var r=t.parentWindow||window.parent;return window===r?new oT:new rT(new Hs(t.parentOrigin),new qs(t.parentOrigin,r),new qs("*",r),((e={})[Bk.FrameLoaded]=tT,e))}const aT=require("intl-messageformat"),sT=require("messageformat");var cT=n.n(sT),uT="en",lT="optimized_checkout",dT=function(){function t(t,e){var n;this._logger=e;var r=this._transformConfig(t),o=r.locale,i=r.locales,a=r.translations;this._locale=o,this._locales=i,this._translations=a,this._formatters={},this._isCspNonceExperimentEnabled=null===(n=t.isCspNonceExperimentEnabled)||void 0===n||n}return t.prototype.mapKeys=function(t){var e=this;Object.keys(t).forEach((function(n){var r="".concat(lT,".").concat(t[n]);e._translations["".concat(lT,".").concat(n)]=e._translations[r]}))},t.prototype.getLocale=function(){return this._hasTranslations()?this._locale:uT},t.prototype.translate=function(t,e){var n;void 0===e&&(e={});var r="".concat(lT,".").concat(t);if("string"!=typeof this._translations[r])return this._logger.warn('Translation key "'.concat(r,'" is missing')),r;if(this._isCspNonceExperimentEnabled){this._formatters[r]||(this._formatters[r]=new aT.IntlMessageFormat(this._escapeSpecialCharacters(this._translations[r]||""),this._locales[r],void 0,{ignoreTag:!0}));try{return this._formatters[r].format(this._transformData(e))}catch(t){if(this._isFormatError(t))return null!==(n=t.originalMessage)&&void 0!==n?n:"";throw t}}if(!this._formatters[r]){var o=new(cT())(this._locales[r]);this._formatters[r]=o.compile(this._translations[r]||"")}return this._formatters[r](this._transformData(e))},t.prototype._transformConfig=function(t){void 0===t&&(t={});var e={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:t.locale||uT},n=t.locales||{},r=this._flattenObject(t.translations||{}),o=this._flattenObject(t.defaultTranslations||{}),i=this._flattenObject(t.fallbackTranslations||{});return(0,l.union)(Object.keys(i),Object.keys(o),Object.keys(r)).forEach((function(a){var s,c;r&&r[a]?(e.translations[a]=r[a],e.locales[a]=n[a]||e.locale):o[a]?(e.translations[a]=o[a],e.locales[a]=null!==(s=t.defaultLocale)&&void 0!==s?s:uT):(e.translations[a]=i[a],e.locales[a]=null!==(c=t.fallbackLocale)&&void 0!==c?c:uT)})),e},t.prototype._flattenObject=function(t,e,n){var r=this;void 0===e&&(e={}),void 0===n&&(n="");try{Object.keys(t).forEach((function(o){var i=t[o],a=n?"".concat(n,".").concat(o):o;if((0,l.isObject)(i))return r._flattenObject(i,e,a);e[a]=i}))}catch(t){this._logger.warn("Unable to parse object: ".concat(t))}return e},t.prototype._transformData=function(t){return Object.keys(t).reduce((function(e,n){var r=t[n];return e[n]=null==r?"":r,e}),{})},t.prototype._hasTranslations=function(){var t=this;return Object.keys(this._locales).map((function(e){return t._locales[e]})).filter((function(e){return e.split("-")[0]===t._locale.split("-")[0]})).length>0},t.prototype._isFormatError=function(t){return"object"==typeof t&&null!==t&&"originalMessage"in t},t.prototype._escapeSpecialCharacters=function(t){return t.replace(/(\w+)='([^']*)'/g,"$1=''$2''")},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const pT=dT;function hT(t){return void 0===t&&(t={}),new pT(t,V())}const fT=function(){function t(t){this._storeConfig=t,this._customerFormatter=new vr(this._storeConfig.shopperCurrency),this._storeFormatter=new vr(this._storeConfig.currency)}return t.prototype.toCustomerCurrency=function(t){var e=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(t*e)},t.prototype.toStoreCurrency=function(t){return this._storeFormatter.format(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();function yT(t){return new fT(t)}var mT=function(){return mT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=8096}function _T(t){return Object.keys(t).reduce((function(e,n){var r=typeof t[n];return"string"===r||"number"===r?vT(vT([],e,!0),["".concat(n,"=").concat(t[n])],!1):"object"===r&&null!==t[n]?vT(vT([],e,!0),[_T(t[n])],!1):e}),[]).join("&")}var ST,CT=function(){return CT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?"1":"0",apm_list:t.join(",")})},t.prototype._getApmSelectedEventOptions=function(t,e){var n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map((function(t){return t.id}));return xT(xT({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:t,apm_location:e?"pre-email section":"payment section"})},t.prototype._getOrderPlacedEventOptions=function(t){var e=this.checkoutService.getState().data.getCart();return xT(xT({},this._getEventCommonOptions()),{selected_payment_method:t,currency_code:(null==e?void 0:e.currency.code)||""})},t}();const MT=DT;function zT(t){return new MT(t)}var RT=function(){return RT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?"1":"0",apm_list:t.join(",")})},t.prototype._getApmSelectedEventOptions=function(t,e){var n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map((function(t){return t.id}));return RT(RT({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:t,apm_location:e?"pre-email section":"payment section"})},t.prototype._getOrderPlacedEventOptions=function(t){var e=this._checkoutService.getState().data.getCart();return RT(RT({},this._getEventCommonOptions()),{selected_payment_method:t,currency_code:(null==e?void 0:e.currency.code)||""})},t}();const FT=NT;function LT(t){return new FT(t)}var BT=function(){function t(t,e){this._host=t,this._hostedFormFactory=e}return t.prototype.submitStoredCard=function(t,e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?t.salePrice:t.listPrice,sku:t.sku,variant_id:t.variantId,discount:t.discountAmount,coupon_amount:t.couponAmount,brand_name:t.brand,currency:e,category_names:(n=t,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?(0,l.flatten)(n.categories).map((function(t){return t.name})):[]),retail_price:t.retailPrice}}));return HT(HT(HT([],n,!0),o,!0),r,!0).map((function(t){return VT(VT({},t),{product_id:String(t.product_id)})}))},t.prototype._hasStepCompleted=function(t){return this._completedSteps[t]},t}();const YT=WT,KT=function(){function t(){}return t.prototype.checkoutBegin=function(){},t.prototype.orderPurchased=function(){},t.prototype.stepCompleted=function(){},t.prototype.customerEmailEntry=function(){},t.prototype.customerSuggestionInit=function(){},t.prototype.customerSuggestionExecute=function(){},t.prototype.customerPaymentMethodExecuted=function(){},t.prototype.showShippingMethods=function(){},t.prototype.selectedPaymentMethod=function(){},t.prototype.clickPayButton=function(){},t.prototype.paymentRejected=function(){},t.prototype.paymentComplete=function(){},t.prototype.exitCheckout=function(){},t}();function JT(t){return function(t){return"bodlEvents"in t}(window)?new YT(t,window.bodlEvents.checkout):new KT}module.exports=r})(); +(()=>{"use strict";var t={483:t=>{t.exports=require("iframe-resizer")},405:t=>{t.exports=require("iframe-resizer/js/iframeResizer.contentWindow")}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,n),i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};n.r(r),n.d(r,{ExtensionCommandType:()=>yd,createBodlService:()=>JT,createBraintreeAnalyticTracker:()=>zT,createCheckoutButtonInitializer:()=>Lk,createCheckoutService:()=>dE,createCurrencyService:()=>yT,createEmbeddedCheckoutMessenger:()=>iT,createLanguageService:()=>hT,createPayPalCommerceAnalyticTracker:()=>LT,createStepTracker:()=>kT,createStoredCardHostedFormService:()=>UT,createTimeout:()=>s.createTimeout,embedCheckout:()=>$k});var o={};n.r(o),n.d(o,{createAmazonPayV2CustomerStrategy:()=>pe,createApplePayCustomerStrategy:()=>Ye,createBoltCustomerStrategy:()=>yn,createBraintreeFastlaneCustomerStrategy:()=>ir,createBraintreePaypalCreditCustomerStrategy:()=>Un,createBraintreePaypalCustomerStrategy:()=>Rn,createBraintreeVisaCheckoutCustomerStrategy:()=>dr,createGooglePayAdyenV2CustomerStrategy:()=>Qr,createGooglePayAdyenV3CustomerStrategy:()=>$r,createGooglePayAuthorizeDotNetCustomerStrategy:()=>ro,createGooglePayBnzCustomerStrategy:()=>bo,createGooglePayBraintreeCustomerStrategy:()=>Jo,createGooglePayCheckoutComCustomerStrategy:()=>fo,createGooglePayCybersourceCustomerStrategy:()=>go,createGooglePayOrbitalCustomerStrategy:()=>Co,createGooglePayPayPalCommerceCustomerStrategy:()=>si,createGooglePayStripeCustomerStrategy:()=>No,createGooglePayStripeUpeCustomerStrategy:()=>Fo,createGooglePayTdOnlineMartCustomerStrategy:()=>fi,createGooglePayWorldpayAccessCustomerStrategy:()=>Uo,createPayPalCommerceCreditCustomerStrategy:()=>ta,createPayPalCommerceCustomerStrategy:()=>Ki,createPayPalCommerceFastlaneCustomerStrategy:()=>xa,createPayPalCommerceVenmoCustomerStrategy:()=>aa,createStripeUPECustomerStrategy:()=>Wa});var i={};n.r(i),n.d(i,{createAdyenV2PaymentStrategy:()=>Wd,createAdyenV3PaymentStrategy:()=>ep,createAffirmPaymentStrategy:()=>cp,createAfterpayPaymentStrategy:()=>bp,createAmazonPayV2PaymentStrategy:()=>Ip,createApplePayPaymentStrategy:()=>Tp,createBlueSnapDirectAPMPaymentStrategy:()=>lh,createBlueSnapDirectCreditCardPaymentStrategy:()=>ah,createBlueSnapV2PaymentStrategy:()=>vh,createBoltPaymentStrategy:()=>kh,createBraintreeAchPaymentStrategy:()=>Nh,createBraintreeFastlanePaymentStrategy:()=>hf,createBraintreeLocalMethodsPaymentStrategy:()=>of,createBraintreePaypalPaymentStrategy:()=>Qh,createCheckoutComAPMPaymentStrategy:()=>$f,createCheckoutComCreditCardPaymentStrategy:()=>Ff,createCheckoutComFawryPaymentStrategy:()=>Af,createCheckoutComIdealPaymentStrategy:()=>Yf,createCheckoutComSepaPaymentStrategy:()=>qf,createClearpayPaymentStrategy:()=>sy,createCreditCardPaymentStrategy:()=>cy,createCyberSourcePaymentStrategy:()=>Ay,createCyberSourceV2PaymentStrategy:()=>Ly,createDigitalRiverPaymentStrategy:()=>Jy,createExternalPaymentStrategy:()=>$y,createGooglePayAdyenV2PaymentStrategy:()=>dm,createGooglePayAdyenV3PaymentStrategy:()=>vm,createGooglePayAuthorizeNetPaymentStrategy:()=>gm,createGooglePayBraintreePaymentStrategy:()=>Im,createGooglePayCheckoutComPaymentStrategy:()=>bm,createGooglePayCybersourcePaymentStrategy:()=>wm,createGooglePayOrbitalPaymentStrategy:()=>_m,createGooglePayPPCPPaymentStrategy:()=>Mm,createGooglePayStripePaymentStrategy:()=>Sm,createGooglePayTdOnlineMartPaymentStrategy:()=>zm,createGooglePayWorldpayAccessPaymentStrategy:()=>Cm,createHummPaymentStrategy:()=>Bm,createKlarnaPaymentStrategy:()=>Zm,createKlarnaV2PaymentStrategy:()=>cv,createLegacyPaymentStrategy:()=>dv,createMolliePaymentStrategy:()=>_v,createMonerisPaymentStrategy:()=>Ev,createNoPaymentStrategy:()=>Tv,createOfflinePaymentStrategy:()=>zv,createOffsitePaymentStrategy:()=>Bv,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>sg,createPayPalCommerceCreditCardsPaymentStrategy:()=>mg,createPayPalCommerceCreditPaymentStrategy:()=>Xv,createPayPalCommerceFastlanePaymentStrategy:()=>xg,createPayPalCommercePaymentStrategy:()=>Hv,createPayPalCommerceRatePayPaymentStrategy:()=>Ig,createPayPalCommerceVenmoPaymentStrategy:()=>ng,createPayPalProPaymentStrategy:()=>Lg,createSagePayPaymentStrategy:()=>qg,createSezzlePaymentStrategy:()=>Hg,createSquareV2PaymentStrategy:()=>ib,createStripeOCSPaymentStrategy:()=>jb,createStripeUPEPaymentStrategy:()=>zb,createStripeV3PaymentStrategy:()=>wb,createTDOnlineMartPaymentStrategy:()=>Jb,createWorldpayAccessPaymentStrategy:()=>rw,createZipPaymentStrategy:()=>uw});var a={};n.r(a),n.d(a,{createAmazonPayV2ButtonStrategy:()=>lA,createApplePayButtonStrategy:()=>bA,createBoltButtonStrategy:()=>SA,createBraintreeVenmoButtonStrategy:()=>FA,createBraintreeVisaCheckoutButtonStrategy:()=>AA,createGooglePayAdyenV2ButtonStrategy:()=>HA,createGooglePayAdyenV3ButtonStrategy:()=>WA,createGooglePayAuthorizeDotNetButtonStrategy:()=>YA,createGooglePayBraintreeButtonStrategy:()=>GA,createGooglePayCheckoutComButtonStrategy:()=>KA,createGooglePayCybersourceButtonStrategy:()=>JA,createGooglePayOrbitalButtonStrategy:()=>ZA,createGooglePayPayPalCommerceButtonStrategy:()=>VA,createGooglePayStripeButtonStrategy:()=>XA,createGooglePayTdOnlineMartButtonStrategy:()=>$A,createGooglePayWorldpayAccessButtonStrategy:()=>QA,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>Ck,createPayPalCommerceButtonStrategy:()=>ik,createPayPalCommerceCreditButtonStrategy:()=>dk,createPayPalCommerceVenmoButtonStrategy:()=>vk,createPaypalExpressButtonStrategy:()=>Fk});const s=require("@bigcommerce/request-sender"),c=require("@bigcommerce/script-loader"),u=require("@bigcommerce/data-store"),l=require("lodash"),d=require("rxjs"),p=require("rxjs/operators");function h(t,e,n){return(r=e)&&r.type&&r.error?(0,d.concat)((0,d.of)(e),(0,d.throwError)((0,u.createErrorAction)(t,e.payload,n))):(0,d.throwError)((0,u.createErrorAction)(t,e,n));var r}var f,y=(f=function(t,e){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},f(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}f(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});const m=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return y(e,t),e}(Error);var v,g=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentProviderCustomer=13]="MissingPaymentProviderCustomer",t[t.MissingPaymentRedirectUrl=14]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=15]="MissingPaymentStatus",t[t.MissingPaymentToken=16]="MissingPaymentToken",t[t.MissingShippingAddress=17]="MissingShippingAddress"}(v||(v={}));const b=function(t){function e(e){var n=t.call(this,function(t){switch(t){case v.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case v.MissingCart:return"Unable to proceed because cart data is unavailable.";case v.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case v.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case v.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case v.MissingCheckoutConfig:case v.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case v.MissingOrder:return"Unable to proceed because order data is unavailable.";case v.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case v.MissingPayment:return"Unable to proceed because payment data is unavailable.";case v.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case v.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case v.MissingPaymentProviderCustomer:return"Unable to proceed because payment provider customer is unavailable.";case v.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return g(e,t),e}(m);var w;!function(t){t.UpdateBillingAddressRequested="UPDATE_BILLING_ADDRESS_REQUESTED",t.UpdateBillingAddressSucceeded="UPDATE_BILLING_ADDRESS_SUCCEEDED",t.UpdateBillingAddressFailed="UPDATE_BILLING_ADDRESS_FAILED",t.ContinueAsGuestRequested="CONTINUE_AS_GUEST_REQUESTED",t.ContinueAsGuestSucceeded="CONTINUE_AS_GUEST_SUCCEEDED",t.ContinueAsGuestFailed="CONTINUE_AS_GUEST_FAILED"}(w||(w={}));var _=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const S=function(t){function e(e){var n=t.call(this,e||"Unable to continue as a guest because the customer is already signed in.")||this;return n.name="UnableToContinueAsGuestError",n.type="unable_to_continue_as_guest",n}return _(e,t),e}(m);var C=function(){return C=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadConfig",null),t}();var X=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Q={body:{},headers:{},status:0},$=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,s=e||Q,c=s.body,u=s.headers,l=s.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=l,a.errors=i||[],a}return X(e,t),e}(m);const tt=$;var et=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const nt=function(t){function e(e){var n=t.call(this,e,{message:e.body.title})||this;return n.name="CheckoutNotAvailableError",n.type="checkout_not_available",n}return et(e,t),e}(tt);var rt="This API endpoint is for internal use only and may change in the future",ot=function(){return ot=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=400&&t.status<500)throw new nt(t);throw t}))},t}();const at=it;var st;!function(t){t.ApplyCouponRequested="APPLY_COUPON_REQUESTED",t.ApplyCouponSucceeded="APPLY_COUPON_SUCCEEDED",t.ApplyCouponFailed="APPLY_COUPON_FAILED",t.RemoveCouponRequested="REMOVE_COUPON_REQUESTED",t.RemoveCouponSucceeded="REMOVE_COUPON_SUCCEEDED",t.RemoveCouponFailed="REMOVE_COUPON_FAILED"}(st||(st={}));var ct=function(){function t(t){this._couponRequestSender=t}return t.prototype.applyCoupon=function(t,e){var n=this;return function(r){return d.Observable.create((function(o){var i=r.getState().checkout.getCheckout();if(!i)throw new b(v.MissingCheckout);o.next((0,u.createAction)(st.ApplyCouponRequested)),n._couponRequestSender.applyCoupon(i.id,t,e).then((function(t){var e=t.body;o.next((0,u.createAction)(st.ApplyCouponSucceeded,e)),o.complete()})).catch((function(t){o.error((0,u.createErrorAction)(st.ApplyCouponFailed,t))}))}))}},t.prototype.removeCoupon=function(t,e){var n=this;return function(r){return d.Observable.create((function(o){var i=r.getState().checkout.getCheckout();if(!i)throw new b(v.MissingCheckout);o.next((0,u.createAction)(st.RemoveCouponRequested)),n._couponRequestSender.removeCoupon(i.id,t,e).then((function(t){var e=t.body;o.next((0,u.createAction)(st.RemoveCouponSucceeded,e)),o.complete()})).catch((function(t){o.error((0,u.createErrorAction)(st.RemoveCouponFailed,t))}))}))}},t}();const ut=ct,lt=["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","customer.customerGroup","payments","promotions.banners"];var dt;function pt(t){return(0,l.uniq)(t).join(",")}!function(t){t.AvailableShippingOptions="consignments.availableShippingOptions",t.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",t.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(dt||(dt={}));var ht=function(){return ht=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0}));a.length>1&&a[0].matches===a[1].matches&&"development"===F()&&V().warn("The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var c=null===(n=i.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();const kt=At;var Tt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const xt=function(t){function e(e){var n,r,o=this.constructor,i=t.call(this,e||"An unexpected error has occurred.")||this;return i.name="StandardError",i.type="standard",n=i,r=o.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(i,o):i.stack=new Error(i.message).stack,i}return Tt(e,t),e}(Error);var Dt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Mt=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return Dt(e,t),e}(xt);var zt,Rt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(zt||(zt={}));const Nt=function(t){function e(e){var n=t.call(this,function(t){switch(t){case zt.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case zt.MissingCart:return"Unable to proceed because cart data is unavailable.";case zt.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case zt.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case zt.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case zt.MissingCheckoutConfig:case zt.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case zt.MissingOrder:return"Unable to proceed because order data is unavailable.";case zt.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case zt.MissingPayment:return"Unable to proceed because payment data is unavailable.";case zt.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case zt.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case zt.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return Rt(e,t),e}(xt);function Ft(t){return e=t.lineItems.physicalItems.filter((function(t){return!t.addedByPromotion})),(0,l.reduce)(e,(function(t,e){return t+e.quantity}),0);var e}function Lt(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}var Bt,jt=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(Bt||(Bt={}));const Ut=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Bt.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Bt.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Bt.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Bt.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e))||this;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return jt(e,t),e}(xt);var qt,Gt,Vt,Ht,Wt,Yt,Kt={de:"eu",jp:"fe",uk:"eu",us:"na"};!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(qt||(qt={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(Gt||(Gt={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(Vt||(Vt={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(Ht||(Ht={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(Wt||(Wt={})),function(t){t.C0001="C0001"}(Yt||(Yt={}));var Jt=function(){return Jt=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(f)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return qe(r,void 0,void 0,(function(){var r,o;return Ge(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=i.sent().body,t.completeMerchantValidation(r),[3,3];case 2:return o=i.sent(),this._onError(o),[3,3];case 3:return[2]}}))}))},t.onshippingcontactselected=function(e){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._handleShippingContactSelected(t,n,e)]}))}))},t.onshippingmethodselected=function(e){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._handleShippingMethodSelected(t,n,e)]}))}))},t.oncancel=function(){return qe(r,void 0,void 0,(function(){var t;return Ge(this,(function(n){switch(n.label){case 0:this._hasApplePaySession=!1,n.label=1;case 1:return n.trys.push([1,4,,5]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 2:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 3:return[2,n.sent()];case 4:return n.sent(),[2,this._onError(new Ne)];case 5:return[2]}}))}))},t.onpaymentauthorized=function(n){return qe(r,void 0,void 0,(function(){return Ge(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return qe(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m,v,g;return Ge(this,(function(b){switch(b.label){case 0:o=this._transformContactToAddress(n.shippingContact),b.label=1;case 1:return b.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return b.sent(),[3,4];case 3:return i=b.sent(),t.abort(),this._hasApplePaySession=!1,[2,this._onError(i)];case 4:if(a=e.storeProfile.storeName,s=this._paymentIntegrationService.getState(),c=s.getCartOrThrow().currency.decimalPlaces,u=s.getCheckoutOrThrow(),l=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=u.consignments[0].availableShippingOptions,p=null==d?void 0:d.find((function(t){return t.id===l})),h=null==d?void 0:d.filter((function(t){return t.id!==l})),f=p?[{label:p.description,amount:"".concat(p.cost.toFixed(c)),detail:p.additionalDescription,identifier:p.id}]:[],h&&Ve(Ve([],h.filter((function(t){return t.isRecommended})),!0),h.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return f.push({label:t.description,amount:"".concat(t.cost.toFixed(c)),detail:t.additionalDescription,identifier:t.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:a,amount:"".concat(u.grandTotal.toFixed(c))},[]),[2];y=d.find((function(t){return t.isRecommended})),m=y?y.id:d[0].id,v=p?p.id:m,b.label=5;case 5:return b.trys.push([5,7,,8]),[4,this._updateShippingOption(v)];case 6:return b.sent(),[3,8];case 7:return g=b.sent(),[2,this._onError(g)];case 8:return s=this._paymentIntegrationService.getState(),u=s.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:f,newTotal:{type:"final",label:a,amount:"".concat(u.grandTotal.toFixed(c))},newLineItems:this._getUpdatedLineItems(u,c)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return qe(this,void 0,void 0,(function(){var r,o,i,a,s,c;return Ge(this,(function(u){switch(u.label){case 0:r=e.storeProfile.storeName,o=n.shippingMethod.identifier,u.label=1;case 1:return u.trys.push([1,3,,4]),[4,this._updateShippingOption(o)];case 2:return u.sent(),[3,4];case 3:return i=u.sent(),t.abort(),this._hasApplePaySession=!1,[2,this._onError(i)];case 4:return a=this._paymentIntegrationService.getState(),s=a.getCartOrThrow().currency.decimalPlaces,c=a.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:r,amount:"".concat(c.grandTotal.toFixed(s))},newLineItems:this._getUpdatedLineItems(c,s)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return qe(this,void 0,void 0,(function(){return Ge(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return qe(this,void 0,void 0,(function(){var n;return Ge(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return qe(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m,v;return Ge(this,(function(g){switch(g.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,s=o.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),l=u.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Fe.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:d=g.sent(),g.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},h=this._transformContactToAddress(a),f=this._transformContactToAddress(s),y=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",g.label=3;case 3:return g.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(Ue(Ue({},h),{email:y,phone:m}))];case 4:return g.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(f)]:[3,6];case 5:g.sent(),g.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return g.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:return v=g.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),[2,this._onError(v)];case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return qe(this,void 0,void 0,(function(){return Ge(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return qe(this,void 0,void 0,(function(){var t,e;return Ge(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Fe.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Fe.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const We=He,Ye=ie((function(t){var e=t.getState().getHost;return new We((0,s.createRequestSender)({host:e()}),t,new Be,new Pe(new ze((0,c.getScriptLoader)(),window)))}),[{id:"applepay"}]);var Ke=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Je=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the client library of a payment method has thrown an unexpected error.")||this;return n.name="PaymentMethodFailedError",n.type="payment_method_client_invalid",n}return Ke(e,t),e}(xt);var Ze=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Xe={body:{},headers:{},status:0},Qe=function(t){function e(e,n){var r=void 0===n?{}:n,o=r.message,i=r.errors,a=this,s=e||Xe,c=s.body,u=s.headers,l=s.status;return(a=t.call(this,o||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=l,a.errors=i||[],a}return Ze(e,t),e}(xt);const $e=Qe;var tn=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const en=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return tn(e,t),e}($e);var nn=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},rn=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&u.lineItems.physicalItems.length>0?[4,this.paymentIntegrationService.updateBillingAddress(_[0])]:[3,9];case 8:A.sent(),A.label=9;case 9:return _.length>0&&u.lineItems.digitalItems.length>0&&0===u.lineItems.physicalItems.length?(I=C[0],P=I.firstName,O=I.lastName,E=$n($n({},_[0]),{firstName:P,lastName:O}),[4,this.paymentIntegrationService.updateBillingAddress(E)]):[3,11];case 10:A.sent(),A.label=11;case 11:return b.length>0&&u.lineItems.physicalItems.length>0?[4,this.paymentIntegrationService.updateShippingAddress(b[0])]:[3,14];case 12:return A.sent(),e&&p?[4,this.setShippingOption()]:[3,14];case 13:A.sent(),A.label=14;case 14:return[3,16];case 15:return A.sent(),[3,16];case 16:return[2]}}))}))},t.prototype.mapPayPalToBcInstrument=function(t,e){if(e)return e.map((function(e){var n=e.id,r=e.paymentSource.card,o=r.brand,i=r.expiry,a=r.lastDigits,s=i.split("-"),c=s[0];return{bigpayToken:n,brand:o,defaultInstrument:!1,expiryMonth:s[1],expiryYear:c,iin:"",last4:a,method:t,provider:t,trustedShippingAddress:!1,type:"card",untrustedShippingCardVerificationMode:Qn.PAN}}))},t.prototype.mapPayPalToBcAddress=function(t,e){if(!t)return[];var n=this.paymentIntegrationService.getState().getCountries()||[];return t.map((function(t){return{id:Date.now(),type:"paypal-address",firstName:t.firstName||"",lastName:t.lastName||"",company:t.company||"",address1:t.streetAddress,address2:t.extendedAddress||"",city:t.locality,stateOrProvince:t.region,stateOrProvinceCode:t.region,country:(r=t.countryCodeAlpha2,o=n.find((function(t){return t.code===r})),(null==o?void 0:o.name)||""),countryCode:t.countryCodeAlpha2,postalCode:t.postalCode,phone:e&&e[0]||"",customFields:[]};var r,o}))},t.prototype.getPayPalBillingAddresses=function(t){var e=t||{},n=e.card,r=e.name;if(n){var o=n.paymentSource.card.billingAddress,i=o.firstName,a=o.lastName,s=r||{},c=s.firstName,u=s.lastName,d=(t||{}).shippingAddress,p=$n($n({},n.paymentSource.card.billingAddress),{firstName:i||c,lastName:a||u});return d&&(0,l.isEqual)(this.normalizeAddress(p),this.normalizeAddress(d))?d:p}},t.prototype.normalizeAddress=function(t){return(0,l.omit)(t,["id"])},t.prototype.mergeShippingAndBillingAddresses=function(t,e){var n=this,r=e.filter((function(e){return!t.some((function(t){return(0,l.isEqual)(n.normalizeAddress(t),n.normalizeAddress(e))}))}));return nr(nr([],t,!0),r,!0)},t.prototype.getMethodIdOrThrow=function(){if(!this.methodId)throw new Mt('Unable to proceed because "methodId" argument is not provided.');return this.methodId},t.prototype.setShippingOption=function(){var t;return tr(this,void 0,void 0,(function(){var e,n,r,o,i;return er(this,(function(a){switch(a.label){case 0:return e=this.paymentIntegrationService.getState(),n=e.getConsignments()||[],r=(null===(t=n[0])||void 0===t?void 0:t.availableShippingOptions)||[],(o=r.find((function(t){return t.isRecommended})))||r.length?(i=o||r[0],[4,this.paymentIntegrationService.selectShippingOption(i.id)]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2]}}))}))},t}();const or=rr,ir=ie((function(t){var e=window,n=new An(new ze((0,c.getScriptLoader)(),e),e),r=new Vn("paypalFastlane"),o=new or(t,n,r);return new Xn(t,o)}),[{id:"braintreeacceleratedcheckout"},{id:"braintree"}]);var ar=function(){return ar=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),r=document.createElement("div");return r.style.display="flex",r.style.flexDirection="column",r.style.visibility="hidden",r.style.width="max-content",r.className=e,r.innerHTML=n,t.appendChild(r),r},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const lr=ur,dr=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new lr(t,(0,mn.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);var pr=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),hr=function(){return hr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}(),br=function(t,e){return!!t&&(!!t.lineItems.physicalItems.some((function(t){return t.isShippingRequired}))||!(!e||!t.lineItems.customItems)&&t.lineItems.customItems.length>0)};var wr,_r,Sr,Cr,Ir,Pr,Or,Er;function Ar(t){return t in Pr}!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(wr||(wr={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(_r||(_r={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(Sr||(Sr={})),function(t){t.pill="pill",t.rect="rect"}(Cr||(Cr={})),function(t){t.ESTIMATED="ESTIMATED",t.FINAL="FINAL",t.NOT_CURRENTLY_KNOWN="NOT_CURRENTLY_KNOWN"}(Ir||(Ir={})),function(t){t.AMEX="AMEX",t.DISCOVER="DISCOVER",t.INTERAC="INTERAC",t.JCB="JCB",t.MC="MASTERCARD",t.VISA="VISA"}(Pr||(Pr={})),function(t){t.OFFER="OFFER",t.PAYMENT_AUTHORIZATION="PAYMENT_AUTHORIZATION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.SHIPPING_OPTION="SHIPPING_OPTION"}(Or||(Or={})),function(t){t.INITIALIZE="INITIALIZE",t.SHIPPING_OPTION="SHIPPING_OPTION",t.SHIPPING_ADDRESS="SHIPPING_ADDRESS",t.OFFER="OFFER"}(Er||(Er={}));var kr=function(){return kr=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?M:void 0,"disable-funding":D.length>0?D:void 0,commit:w,components:oi(oi(["buttons","hosted-fields","messages","payment-fields","legal"],z,!0),I,!0),currency:e,intent:a},f&&{"buyer-country":u}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=ei(ei({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const ai=ii,si=ie((function(t){return new Ur(t,new Yr(Xr(),new ti(t,new ai((0,c.getScriptLoader)())),(0,s.createRequestSender)(),(0,mn.createFormPoster)()))}),[{id:"googlepaypaypalcommerce"}]);function ci(){var t,e=window.navigator;return t=e.language?e.language:e.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof e.javaEnabled&&e.javaEnabled(),language:t,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var ui=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),li=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},di=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&(e.style.display="none")},t}();const ki=Ai;var Ti="This API endpoint is for internal use only and may change in the future",xi=function(){return xi=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?z:void 0,"disable-funding":M.length>0?M:void 0,commit:w,components:Bi(Bi(["buttons","hosted-fields","payment-fields","legal"],x,!0),D,!0),currency:e,intent:a},f&&{"buyer-country":u}),attributes:{"data-partner-attribution-id":l,"data-client-token":o}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=Ni(Ni({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const Ui=ji,qi=function(t){var e=t.getState().getHost;return new ki((0,mn.createFormPoster)(),t,new Ri((0,s.createRequestSender)({host:e()})),new Ui((0,c.getScriptLoader)()))};var Gi=function(){return Gi=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(s=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(i),[4,this.paymentIntegrationService.updateShippingAddress(s)]):[3,6];case 4:return u.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:u.sent(),u.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return u.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return u.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return c=u.sent(),this.handleError(c),[3,10];case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Vi(this,void 0,void 0,(function(){var e,n,r;return Hi(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:return r=o.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Vi(this,void 0,void 0,(function(){var e,n;return Hi(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const Yi=Wi,Ki=ie((function(t){return new Yi(t,qi(t))}),[{id:"paypalcommerce"}]);var Ji=function(){return Ji=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(s=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(i),[4,this.paymentIntegrationService.updateShippingAddress(s)]):[3,6];case 4:return u.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:u.sent(),u.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return u.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return u.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return c=u.sent(),this.handleError(c),[3,10];case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return Zi(this,void 0,void 0,(function(){var e,n,r;return Xi(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:return r=o.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return Zi(this,void 0,void 0,(function(){var e,n;return Xi(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},t.prototype.handleError=function(t){if("function"!=typeof this.onError)throw t;this.onError(t)},t}();const $i=Qi,ta=ie((function(t){return new $i(t,qi(t))}),[{id:"paypalcommercecredit"}]);var ea=function(){return ea=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?h:void 0,"disable-funding":f.length>0?f:void 0,commit:!0,components:["buttons","payment-fields"],currency:e,intent:r},c&&{"buyer-country":a}),attributes:{"data-partner-attribution-id":s,"data-namespace":"paypalApms"}}},t.prototype.getPayPalSdkMessagesConfiguration=function(t,e){var n=t.initializationData;if(!n||!n.clientId)throw new Nt(zt.MissingPaymentMethod);var r=n.clientId,o=n.merchantId,i=n.attributionId,a=n.isDeveloperModeApplicable,s=n.buyerCountry;return{options:sa({"client-id":r,"merchant-id":o,components:["messages"],currency:e},a&&{"buyer-country":s}),attributes:{"data-namespace":"paypalMessages","data-partner-attribution-id":i}}},t.prototype.transformConfig=function(t){var e={};return Object.keys(t).forEach((function(n){var r,o=t[n];null==o||""===o||Array.isArray(o)&&0===o.length||(e=sa(sa({},e),((r={})[n]=Array.isArray(o)?o.join(","):o,r)))})),e},t}();const da=la;function pa(){return new da((0,c.createScriptLoader)())}var ha,fa,ya,ma,va;!function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(ha||(ha={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(fa||(fa={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(ya||(ya={})),function(t){t.pill="pill",t.rect="rect"}(ma||(ma={})),function(t){t.SUCCEEDED="succeeded",t.FAILED="failed",t.CANCELED="cancelled",t.UNRECOGNIZED="unrecognized"}(va||(va={}));var ga=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},ba=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this.paymentIntegrationService.updateShippingAddress(u)]:[3,6];case 4:return d=b.sent(),p=d.getPaymentMethodOrThrow(t),h=(p.initializationData||{}).isFastlaneShippingOptionAutoSelectEnabled,f=d.getConsignments()||[],y=(null===(n=f[0])||void 0===n?void 0:n.availableShippingOptions)||[],m=y[0],((v=y.find((function(t){return t.isRecommended})))||m)&&h?(g=(null==v?void 0:v.id)||m.id,[4,this.paymentIntegrationService.selectShippingOption(g)]):[3,6];case 5:b.sent(),b.label=6;case 6:return[2]}}))}))},t.prototype.getFastlaneStyles=function(t,e){var n=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{},r=n.fastlaneStyles;return Oa(n.isFastlaneStylingEnabled?r:{},null==e?void 0:e.styles)},t}();const Ta=ka,xa=ie((function(t){return new Ta(t,pa(),Ca())}),[{id:"paypalcommerceacceleratedcheckout"},{id:"paypalcommercecreditcards"}]);function Da(t){return"stripeLinkAuthenticationState"in t}function Ma(t){return"object"==typeof t&&null!==t&&"initializationData"in t&&void 0!==t.initializationData&&null!==t.initializationData&&"object"==typeof t.initializationData&&"stripePublishableKey"in t.initializationData&&"stripeConnectedAccount"in t.initializationData&&"shopperLanguage"in t.initializationData&&void 0!==t.initializationData.stripePublishableKey&&void 0!==t.initializationData.stripeConnectedAccount&&void 0!==t.initializationData.shopperLanguage}var za,Ra,Na,Fa,La,Ba;!function(t){t.SHIPPING="shipping",t.BILLING="billing"}(za||(za={})),function(t){t.SPLIT="split",t.FULL="full",t.ORGANIZATION="organization"}(Ra||(Ra={})),function(t){t.CreditCard="card",t.Link="link",t.SOFORT="sofort",t.EPS="eps",t.GRABPAY="grabpay",t.BANCONTACT="bancontact",t.IDEAL="ideal",t.GIROPAY="giropay",t.ALIPAY="alipay",t.KLARNA="klarna",t.OCS="stripe_ocs"}(Na||(Na={})),function(t){t.NEVER="never",t.AUTO="auto",t.ALWAYS="always",t.PAYMENT="payment",t.IF_REQUIRED="if_required"}(Fa||(Fa={})),function(t){t.PAYMENT="payment",t.AUTHENTICATION="linkAuthentication",t.SHIPPING="address"}(La||(La={})),function(t){t.REQUIRES_PAYMENT_METHOD="requires_payment_method",t.REQUIRES_CONFIRMATION="requires_confirmation",t.REQUIRES_ACTION="requires_action",t.PROCESSING="processing",t.SUCCEEDED="succeeded",t.CANCELED="canceled"}(Ba||(Ba={}));var ja=function(){function t(t,e){this.paymentIntegrationService=t,this.scriptLoader=e}return t.prototype.initialize=function(t){var e,n,r,o,i;return n=this,r=void 0,i=function(){var n,r,o,i,a,s,c,u,l,d,p,h,f,y,m,v,g,b,w,_,S,C,I,P,O,E,A,k,T,x=this;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=400&&t.status<500)throw new nt(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,o=r.params,i=(void 0===o?{}:o).include,a=r.timeout,s="/api/storefront/checkout/".concat(t),c=as({Accept:E.JsonV1},A);return this._requestSender.put(s,{params:{include:is(lt,i)},body:e,headers:c,timeout:a})},t}();const cs=ss;var us;!function(t){t.LoadCheckoutRequested="LOAD_CHECKOUT_REQUESTED",t.LoadCheckoutSucceeded="LOAD_CHECKOUT_SUCCEEDED",t.LoadCheckoutFailed="LOAD_CHECKOUT_FAILED",t.UpdateCheckoutRequested="UPDATE_CHECKOUT_REQUESTED",t.UpdateCheckoutSucceeded="UPDATE_CHECKOUT_SUCCEEDED",t.UpdateCheckoutFailed="UPDATE_CHECKOUT_FAILED"}(us||(us={}));var ls=function(){return ls=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadFormFields",null),t}();const ys=fs;var ms=function(){return ms=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([J],t.prototype,"loadPaymentMethod",null),t}();const Cs=Ss;var Is=function(){return Is=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0&&n.splice(r,1)}},t.prototype.trigger=function(t,e){var n=this._listeners[t.type];n&&n.forEach((function(n){return e?n(t,e):n(t)}))},t.prototype._handleMessage=function(t){if(-1!==this._sourceOrigins.indexOf(t.origin)&&js(t.data,t.data.type)){var e=t.data,n=e.context,r=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleMessage",null),t}();const Hs=Vs;var Ws=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Ys=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return Ws(e,t),e}(m);var Ks=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Js=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return Ks(e,t),e}(m);var Zs=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const Xs=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return Zs(e,t),e}(m);var Qs=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},$s=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]3&&!s?a:"".concat(a," ").concat("/"," ").concat(s)},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*".concat("/","\\s*"))),n=e[0],r=void 0===n?"":n,o=e[1],i=void 0===o?"":o;return/^\d+$/.test(r)&&/^\d+$/.test(i)?{month:1===r.length?"0".concat(r):r.slice(0,2),year:2===i.length?"20".concat(i):i.slice(0,4)}:{month:"",year:""}},t}();const hu=pu,fu=require("card-validator"),yu=function(){function t(){}return t.prototype.format=function(t){var e=(0,fu.number)(t).card;if(!e)return t;var n=(0,l.max)((0,fu.creditCardType)(t).map((function(t){return(0,l.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,fu.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();var mu=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new b(v.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,l.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"==typeof t&&"address"in t},t}();const Bu=Lu;var ju=function(){return ju=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),r=document.createElement("div");return r.style.display="flex",r.style.flexDirection="column",r.style.visibility="hidden",r.className=e,r.innerHTML=n,t.appendChild(r),r},t}();const Kl=Yl;var Jl=function(){function t(t,e){this._store=t,this._customerActionCreator=e}return t.prototype.signIn=function(t,e){return this._store.dispatch(this._customerActionCreator.signInCustomer(t,e))},t.prototype.signOut=function(t){return this._store.dispatch(this._customerActionCreator.signOutCustomer(t))},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t}();const Zl=Jl;function Xl(t){return"".concat(window.location.origin,"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=").concat(t)}var Ql={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function $l(t){var e=t.replace("-","_").toLowerCase().split("_"),n=e[0],r=e[1],o="".concat(n,"_").concat(r),i=Ql[n];return i?i.indexOf(o)>-1?o:i[0]:"en_us"}var td=function(){function t(t,e,n,r,o){this._store=t,this._paymentMethodActionCreator=e,this._remoteCheckoutActionCreator=n,this._masterpassScriptLoader=r,this._locale=o}return t.prototype.initialize=function(t){var e=this,n=t.masterpass,r=t.methodId;if(!n||!r)throw new Pt('Unable to proceed because "options.masterpass" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(t){if(e._paymentMethod=t.paymentMethods.getPaymentMethod(r),!e._paymentMethod||!e._paymentMethod.initializationData.checkoutId)throw new b(v.MissingPaymentMethod);var o=t.cart.getCart();if(!o)throw new b(v.MissingCart);var i=n.container,a={checkoutId:e._paymentMethod.initializationData.checkoutId,allowedCardTypes:e._paymentMethod.initializationData.allowedCardTypes,amount:o.cartAmount.toString(),currency:o.currency.code,cartId:o.id,suppressShippingAddress:!1,callbackUrl:Xl("checkout")},s={useMasterpassSrc:e._paymentMethod.initializationData.isMasterpassSrcEnabled,language:$l(e._locale),testMode:e._paymentMethod.config.testMode,checkoutId:e._paymentMethod.initializationData.checkoutId};return e._masterpassScriptLoader.load(s).then((function(t){e._signInButton=e._createSignInButton(i),e._signInButton.addEventListener("click",(function(){t.checkout(a)}))}))})).then((function(){return e._store.getState()}))},t.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._signInButton&&this._signInButton.parentNode&&(this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve(this._store.getState())},t.prototype.signIn=function(){throw new Wl('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},t.prototype.signOut=function(t){var e=this._store.getState().payment.getPaymentId();return e?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e.providerId,t)):Promise.resolve(this._store.getState())},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t.prototype._createSignInButton=function(t){var e=document.querySelector("#".concat(t));if(!this._paymentMethod||!this._paymentMethod.initializationData.checkoutId)throw new b(v.MissingPaymentMethod);if(!e)throw new Pt("Unable to create sign-in button without valid container ID.");var n=document.createElement("input");if(n.type="image",this._paymentMethod.initializationData.isMasterpassSrcEnabled){var r=this._paymentMethod.config.testMode?"sandbox.":"",o=this._paymentMethod.initializationData.checkoutId,i=["locale=".concat($l(this._locale)),"paymentmethod=master,visa,amex,discover","checkoutid=".concat(o)];n.src=["https://".concat(r,"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg"),i.join("&")].join("?")}else n.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(n),n},t}();const ed=td;var nd=function(){function t(t,e){this._store=t,this._remoteCheckoutActionCreator=e}return t.prototype.signIn=function(){throw new Wl('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},t.prototype.signOut=function(t){var e=this._store.getState().payment.getPaymentId();return e?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(e.providerId,t)):Promise.resolve(this._store.getState())},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t.prototype.executePaymentMethodCheckout=function(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve(this._store.getState())},t}();const rd=nd;var od,id,ad=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),sd=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to no extension configured for this region.")||this;return n.name="ExtensionNotFoundError",n.type="extension_not_found",n}return ad(e,t),e}(m);function cd(t){var e,n=null===(e=document.querySelector('[data-extension-id="'.concat(t.id,'"]')))||void 0===e?void 0:e.querySelector("iframe");if(!(null==n?void 0:n.contentWindow))throw new sd("Unable to post due to no extension rendered for ID: ".concat(t.id,"."));return new qs(t.url,n.contentWindow)}function ud(t,e){return(0,n(483).iframeResizer)(t,e)}!function(t){t.LoadExtensionsRequested="LOAD_EXTENSIONS_REQUESTED",t.LoadExtensionsSucceeded="LOAD_EXTENSIONS_SUCCEEDED",t.LoadExtensionsFailed="LOAD_EXTENSIONS_FAILED",t.RenderExtensionRequested="RENDER_EXTENSION_REQUESTED",t.RenderExtensionSucceeded="RENDER_EXTENSION_SUCCEEDED",t.RenderExtensionFailed="RENDER_EXTENSION_FAILED"}(od||(od={})),function(t){t.ExtensionReady="EXTENSION:READY",t.ExtensionFailed="EXTENSION:FAILED"}(id||(id={}));var ld,dd=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),pd=function(t){function e(e){var n=t.call(this,e||"Unable to load an extension")||this;return n.name="ExtensionNotLoadedError",n.type="extension_not_loaded",n}return dd(e,t),e}(m);!function(t){t.Subscribe="EXTENSION_INTERNAL:SUBSCRIBE",t.Unsubscribe="EXTENSION_INTERNAL:UNSUBSCRIBE",t.ResizeIframe="EXTENSION_INTERNAL:RESIZE_IFRAME"}(ld||(ld={}));var hd=function(){function t(t){this._options=t}return t.prototype.createFrame=function(t,e,n,r){var o=document.getElementById(e),i=(this._options||{}).timeout,a=void 0===i?6e4:i;if(!o)throw new pd("Unable to embed the iframe because the container element could not be found.");var s=document.createElement("iframe");return s.src=t,s.style.border="none",s.style.display="none",s.style.width="100%",o.appendChild(s),this._toResizableFrame(s,a,n,r).catch((function(t){throw o.removeChild(s),t}))},t.prototype._toResizableFrame=function(t,e,n,r){return o=this,i=void 0,s=function(){var o,i;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&(n[e.code]={discount_amount:t.toInteger(e.discountedAmount),discount_display_name:e.displayName})})),e.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:t.toInteger(e.discountAmount),discount_display_name:"discount"}),n},t.prototype.getCategories=function(t){return t?t.map((function(t){return t.map((function(t){return t.name}))})):[[]]},t}();const ip=op;var ap;!function(t){t.PROD="//cdn1.affirm.com/js/v2/affirm.js",t.SANDBOX="//cdn1-sandbox.affirm.com/js/v2/affirm.js"}(ap||(ap={}));const sp=function(){function t(t){void 0===t&&(t=window),this.affirmWindow=t}return t.prototype.load=function(t,e){void 0===t&&(t="");var n=e?ap.SANDBOX:ap.PROD;if(function(t,e,n,r,o,i,a){var s=t[n]||{},c=document.createElement(i),u=document.getElementsByTagName(i)[0],l=function(t,e,n){return function(){t[e]._.push([n,arguments])}};s[r]=l(s,r,"set");var d=s[r];s[o]={},s[o]._=[],d._=[],s._=[],s[o][a]=l(s,o,a),s.jsReady=function(){s._.push([a,arguments])};for(var p=0,h="set add save post open empty reset on off trigger ready setProduct".split(" ");p0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,h=o.getCheckoutOrThrow().outstandingBalance;return{paymentType:t,amount:h,fallback:{url:"url-placeholder",buttonText:"button placeholder"},currencyCode:l.code,shippingAddressRequired:p,email:d,givenName:s,surname:c,address:{countryCode:u},onPaymentStart:function(o,i){return tf(r,void 0,void 0,(function(){var r,a,s,c;return ef(this,(function(u){switch(u.label){case 0:return this.isLPMsUpdateExperimentEnabled?[4,this.getLPMsBasicPaymentData()]:(this.orderId=o.paymentId,i(),[2]);case 1:r=u.sent(),a=$h($h({},r),{formattedPayload:(c={method:t},c["".concat(t,"_account")]={order_id:o.paymentId},c)}),u.label=2;case 2:return u.trys.push([2,5,,6]),[4,this.paymentIntegrationService.submitOrder(e,n)];case 3:return u.sent(),[4,this.paymentIntegrationService.submitPayment({methodId:t,paymentData:a})];case 4:return u.sent(),[3,6];case 5:if(s=u.sent(),this.isBraintreeOrderSavedResponse(s)&&s.body.additional_action_required.data.order_id_saved_successfully)return i(),[2];throw s;case 6:return[2]}}))}))}}},t.prototype.getInstantLPMCallback=function(t,e,n,r,o){var i=this,a=this.paymentIntegrationService.getState().getCartOrThrow();return function(s,c){return tf(i,void 0,void 0,(function(){var i,u,l,d;return ef(this,(function(p){switch(p.label){case 0:return s?"LOCAL_PAYMENT_WINDOW_CLOSED"===s.code?(this.toggleLoadingIndicator(!1),[2,e()]):(this.toggleLoadingIndicator(!1),[2,e(new en)]):[4,this.getLPMsBasicPaymentData()];case 1:i=p.sent(),u=$h($h({},i),{formattedPayload:(d={method:n},d["".concat(n,"_account")]=$h({email:a.email,token:c.nonce},this.isLPMsUpdateExperimentEnabled?{}:{order_id:this.orderId}),d)}),p.label=2;case 2:return p.trys.push([2,6,,7]),this.isLPMsUpdateExperimentEnabled?[3,4]:[4,this.paymentIntegrationService.submitOrder(r,o)];case 3:p.sent(),p.label=4;case 4:return[4,this.paymentIntegrationService.submitPayment({methodId:n,paymentData:u})];case 5:return p.sent(),[2,t(void 0)];case 6:return l=p.sent(),this.handleError(l),[2,e(l)];case 7:return[2]}}))}))}},t.prototype.toggleLoadingIndicator=function(t){t&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},t.prototype.handleError=function(t){var e=(this.braintreelocalmethods||{}).onError;this.toggleLoadingIndicator(!1),e&&"function"==typeof e&&e(t)},t.prototype.isNonInstantPaymentMethod=function(t){return t.toUpperCase()in be},t.prototype.isBraintreeRedirectError=function(t){var e;if("object"!=typeof t||null===t)return!1;var n=t.body;return!!n&&!!(null===(e=n.additional_action_required)||void 0===e?void 0:e.data.redirect_url)},t.prototype.isBraintreeOrderSavedResponse=function(t){var e;if("object"!=typeof t||null===t)return!1;var n=t.body;return!!n&&(null===(e=n.additional_action_required)||void 0===e?void 0:e.data.hasOwnProperty("order_id_saved_successfully"))},t}();const rf=nf,of=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new rf(t,n,new Gh({styles:{backgroundColor:"black"}}))}),[{gateway:"braintreelocalmethods"}]);function af(t){return!!t&&("authenticationState"in t||"addresses"in t||"instruments"in t)}var sf=function(){return sf=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this.paymentIntegrationService.updatePaymentProviderCustomer(sf(sf({},a),{instruments:lf([],s,!0)}))]:[3,3]):[3,3];case 2:return c.sent(),[2,s[0]];case 3:return[2,void 0]}}))}))},t}();const pf=df,hf=ie((function(t){var e=window,n=new An(new ze((0,c.getScriptLoader)(),e),e),r=new Vn("paypalFastlane"),o=new or(t,n,r);return new pf(t,o,r)}),[{id:"braintreeacceleratedcheckout"}]);var ff=function(){return ff=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?i(new Je(t.ErrorDescription)):t.Payment&&t.Payment.ExtendedData&&t.Payment.ExtendedData.SignatureVerification===by.Yes?o({token:e}):i(new Je("Transaction signature could not be validated."));case yy.Failure:return i(new Je("User failed authentication or an error was encountered while processing the transaction."));case yy.Error:return i(new Je(t.ErrorDescription))}}));var a={AcsUrl:t.acs_url,Payload:t.merchant_data},s=n._mapToPartialOrder(e,t.payer_auth_request);r.continue(gy.CCA,a,s)}))}))},t.prototype._mapToPartialOrder=function(t,e){var n={BillingAddress:this._mapToCardinalAddress(t.billingAddress)};return t.paymentData&&(n.Account=this._mapToCardinalAccount(t.paymentData)),t.billingAddress.email&&(n.Email1=t.billingAddress.email),t.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(t.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:t.id,Amount:t.amount,CurrencyCode:t.currencyCode,OrderChannel:"S",TransactionId:e}}},t.prototype._mapToCardinalAccount=function(t){return{AccountNumber:Number(t.ccNumber),ExpirationMonth:Number(t.ccExpiry.month),ExpirationYear:Number(t.ccExpiry.year),NameOnAccount:t.ccName,CardCode:Number(t.ccCvv)}},t.prototype._mapToCardinalAddress=function(t){var e={FirstName:t.firstName,LastName:t.lastName,Address1:t.address1,City:t.city,State:t.stateOrProvince,PostalCode:t.postalCode,CountryCode:t.countryCode};return t.address2&&(e.Address2=t.address2),t.phone&&(e.Phone1=t.phone),e},t.prototype._getClientSDK=function(){if(!this._sdk)throw new Ut(Bt.PaymentNotInitialized);return this._sdk},t}();const Sy=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(t,e){var n=this,r=e?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript("".concat(r,"?v=").concat(t)).then((function(){if(!n._window.Cardinal)throw new ee;return n._window.Cardinal}))},t}();var Cy=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Iy=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},Py=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0){var i=this.getInitializeOptions().containerId;if(i){var a=document.getElementById(i);if(a){var s=document.createElement("p");s.setAttribute("id","".concat(n,"-").concat(e,"-paragraph")),t.unsupportedMethodMessage&&(s.innerText=t.unsupportedMethodMessage,a.appendChild(s),t.disableButton(!0))}}}}},t}();const gv=vv;var bv=function(){function t(t,e){void 0===e&&(e=window),this.scriptLoader=t,this.mollieHostWindow=e}return t.prototype.load=function(t,e,n){return r=this,o=void 0,a=function(){return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]-1?i:o[0]}var Ab=function(){return Ab=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?i(new Je(t.ErrorDescription)):t.Payment&&t.Payment.ExtendedData&&t.Payment.ExtendedData.SignatureVerification===M_.Yes?o({token:e}):i(new Je("Transaction signature could not be validated."));case k_.Failure:return i(new Je("User failed authentication or an error was encountered while processing the transaction."));case k_.Error:return i(new Je(t.ErrorDescription))}}));var a={AcsUrl:t.acs_url,Payload:t.merchant_data},s=n._mapToPartialOrder(e,t.payer_auth_request);r.continue(D_.CCA,a,s)}))}))},t.prototype._mapToPartialOrder=function(t,e){var n={BillingAddress:this._mapToCardinalAddress(t.billingAddress)};return t.paymentData&&(n.Account=this._mapToCardinalAccount(t.paymentData)),t.billingAddress.email&&(n.Email1=t.billingAddress.email),t.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(t.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:t.id,Amount:t.amount,CurrencyCode:t.currencyCode,OrderChannel:"S",TransactionId:e}}},t.prototype._mapToCardinalAccount=function(t){return{AccountNumber:Number(t.ccNumber),ExpirationMonth:Number(t.ccExpiry.month),ExpirationYear:Number(t.ccExpiry.year),NameOnAccount:t.ccName,CardCode:Number(t.ccCvv)}},t.prototype._mapToCardinalAddress=function(t){var e={FirstName:t.firstName,LastName:t.lastName,Address1:t.address1,City:t.city,State:t.stateOrProvince,PostalCode:t.postalCode,CountryCode:t.countryCode};return t.address2&&(e.Address2=t.address2),t.phone&&(e.Phone1=t.phone),e},t.prototype._getClientSDK=function(){if(!this._sdk)throw new oc(nc.PaymentNotInitialized);return this._sdk},t}();var N_=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(t,e){var n=this,r=e?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript("".concat(r,"?v=").concat(t)).then((function(){if(!n._window.Cardinal)throw new Ul;return n._window.Cardinal}))},t}();const F_=N_;var L_=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();const B_=function(t){function e(e){var n=t.call(this,e||"The selected payment method was declined. Please select another payment method.")||this;return n.name="PaymentMethodDeclinedError",n.type="payment_declined",n}return L_(e,t),e}(m);var j_="ACKNOWLEDGE",U_="FINALIZE",q_=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),G_=function(){return G_=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleWalletButtonClick",null),t}();var tS;function eS(t){var e;return!!(null===(e=t.initializationData)||void 0===e?void 0:e.widgetConfig)}!function(t){t.FORM_POST="FormPost",t.WAIT_FOR_CUSTOMER="WaitForCustomer"}(tS||(tS={}));var nS,rS=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t.InvalidCart="invalid_cart"}(nS||(nS={}));const oS=function(t){function e(e,n){var r=t.call(this,function(t,e){return t===nS.InvalidCart?"Cart price is different to ".concat(e," plan amount."):"There was an error while processing your payment. Please try again or contact us."}(e,n))||this;return r.name="OpyError",r.type="opy_error",r.subtype=e,r}return rS(e,t),e}(m);var iS=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},aS=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0},t.prototype.setCompleted=function(t){var e=this.getCompletedPayments();e.push(t),this.setCompletedPayments(e)},t.prototype.getCompletedPayments=function(){return this._browserStorage.getItem(ES)||[]},t.prototype.setCompletedPayments=function(t){this._browserStorage.setItem(ES,t)},t}(),kS=function(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))},TS=function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]Date.now()}((e=new Date(t.vaultAccessExpiry),(n=new Date(e.getTime())).setMinutes(e.getMinutes()+2),n));var e,n},t.prototype._getCurrentAccessToken=function(t){var e=t.getState().instruments.getInstrumentsMeta();if(e)return{vaultAccessToken:e.vaultAccessToken,vaultAccessExpiry:e.vaultAccessExpiry}},t.prototype._getValidAccessToken=function(t){return t&&this._isValidVaultAccessToken(t)?Promise.resolve(t):this._instrumentRequestSender.getVaultAccessToken().then((function(t){return t.body}))},t.prototype._getShippingAddress=function(t){var e=t.getState(),n=e.shippingAddress.getShippingAddresses();return n.length>1?n:e.shippingAddress.getShippingAddress()},t.prototype._getSessionContext=function(t){var e=t.getState(),n=e.config.getStoreConfig(),r=e.cart.getCart();if(!n)throw new b(v.MissingCheckoutConfig);if(!r)throw new b(v.MissingCart);return{customerId:r.customerId,storeId:n.storeProfile.storeId,currencyCode:(n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency).code}},t}();const ZS=JS;var XS=function(){return XS=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(I))]:[3,10];case 9:k.sent(),k.label=10;case 10:return[2]}}))}))},t.prototype._getPayPalBillingAddress=function(t){var e=t.name,n=t.card.paymentSource.card.billingAddress;return _C(_C({},n),{firstName:n.firstName||(null==e?void 0:e.firstName),lastName:n.lastName||(null==e?void 0:e.lastName)})},t.prototype._getCountryNameByCountryCode=function(t,e){var n=e.find((function(e){return e.code===t}));return(null==n?void 0:n.name)||""},t.prototype._mapPayPalToBcAddress=function(t,e,n,r){return{id:Number(Date.now()),type:"paypal-address",firstName:t.firstName||"",lastName:t.lastName||"",company:t.company||"",address1:t.streetAddress,address2:t.extendedAddress||"",city:t.locality,stateOrProvince:t.region,stateOrProvinceCode:t.region,country:this._getCountryNameByCountryCode(t.countryCodeAlpha2,e),countryCode:t.countryCodeAlpha2,postalCode:t.postalCode,phone:n||"",customFields:r||[]}},t.prototype._normalizeAddress=function(t){return(0,l.omit)(t,["id"])},t.prototype._mergeShippingAndBillingAddresses=function(t,e){return(0,l.isEqual)(this._normalizeAddress(t),this._normalizeAddress(e))?[t]:[t,e]},t.prototype._mapPayPalToBcInstrument=function(t,e){if(e){var n=e.id,r=e.paymentSource.card,o=r.brand,i=r.expiry,a=r.lastDigits,s=i.split("-"),c=s[0];return{bigpayToken:n,brand:o,defaultInstrument:!1,expiryMonth:s[1],expiryYear:c,iin:"",last4:a,method:t,provider:t,trustedShippingAddress:!1,untrustedShippingCardVerificationMode:wC.CVV,type:"card"}}},t.prototype._handleBraintreeFastlaneShippingAddressChange=function(){return SC(this,void 0,void 0,(function(){var t,e,n,r,o,i,a,s,c,u,l;return CC(this,(function(d){switch(d.label){case 0:return t=this._store.getState(),e=t.countries.getCountries()||[],[4,this._braintreeIntegrationService.getBraintreeFastlane()];case 1:return[4,d.sent().profile.showShippingAddressSelector()];case 2:return n=d.sent(),r=n.selectionChanged,o=n.selectedAddress,r?(i=this._store.getState(),a=i.shippingAddress.getShippingAddressesOrThrow(),s=i.paymentProviderCustomer.getPaymentProviderCustomer(),c=af(s)?s:{},(u=this._mapPayPalToBcAddress(o,e,o.phoneNumber,a[0].customFields))?(l=this._filterAddresses(IC([u],c.addresses||[],!0)),[4,this._store.dispatch(this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(_C(_C({},c),{addresses:l})))]):[3,5]):[3,5];case 3:return d.sent(),[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(u))];case 4:return d.sent(),[2,u];case 5:return[2,void 0]}}))}))},t.prototype._filterAddresses=function(t){var e=this;return t.reduce((function(t,n){return n?t.some((function(t){return e._isEqualAddresses(t,n)}))?t:IC(IC([],t,!0),[n],!1):t}),[])},t.prototype._isEqualAddresses=function(t,e){return(0,l.isEqual)(this._normalizeAddress(t),this._normalizeAddress(e))},t.prototype._shouldUseBraintreeFastlaneShippingComponent=function(t){var e;return SC(this,void 0,void 0,(function(){var n,r,o,i;return CC(this,(function(a){switch(a.label){case 0:return n=this._store.getState(),r=n.paymentProviderCustomer.getPaymentProviderCustomer(),(o=af(r)?r:{})&&o!==me.CANCELED?[4,this._getBraintreePaymentMethodOrThrow(t)]:[3,2];case 1:return i=a.sent(),[2,!!(null===(e=null==i?void 0:i.initializationData)||void 0===e?void 0:e.isFastlaneEnabled)];case 2:return[2,!1]}}))}))},t.prototype._getBraintreePaymentMethodOrThrow=function(t){return SC(this,void 0,void 0,(function(){var e,n;return CC(this,(function(r){switch(r.label){case 0:return e=this._store.getState(),(n=e.paymentMethods.getPaymentMethod(t))?[3,2]:[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t))];case 1:return[2,r.sent().paymentMethods.getPaymentMethodOrThrow(t)];case 2:return[2,n]}}))}))},t}();const OC=PC,EC=function(){function t(t,e){this._store=t,this._consignmentActionCreator=e}return t.prototype.updateAddress=function(t,e){return this._store.dispatch(this._consignmentActionCreator.updateAddress(t,e))},t.prototype.selectOption=function(t,e){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(t,e))},t.prototype.initialize=function(){return Promise.resolve(this._store.getState())},t.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},t}();var AC=function(){return AC=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?[4,this._store.dispatch(this._consignmentActionCreator.updateAddress(f))]:[3,7];case 6:v.sent(),v.label=7;case 7:return[2]}}))}))},t.prototype._handlePayPalShippingAddressChange=function(){return kC(this,void 0,void 0,(function(){var t,e,n,r,o,i,a,s,c;return TC(this,(function(u){switch(u.label){case 0:return[4,this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow().profile.showShippingAddressSelector()];case 1:return t=u.sent(),e=t.selectionChanged,n=t.selectedAddress,e?(r=this._store.getState(),o=r.shippingAddress.getShippingAddressesOrThrow(),i=r.paymentProviderCustomer.getPaymentProviderCustomer(),a=Pg(i)?i:{},s=this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(n.address,n.name,n.phoneNumber,o[0].customFields),c=this._paypalCommerceFastlaneUtils.filterAddresses(function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const ZC=JC,XC=require("reselect");var QC=function(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o0}})),J=tI(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===j_||t()===U_}})),(0,H.memoizeOne)((function(t,e){return{getPaymentId:B({checkout:t,order:e}),getPaymentIdOrThrow:j({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:q({checkout:t,order:e}),getPaymentToken:G({checkout:t,order:e}),getPaymentTokenOrThrow:V({checkout:t,order:e}),getPaymentRedirectUrl:W({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:Y({checkout:t,order:e}),isPaymentDataRequired:K({checkout:t,order:e}),isPaymentDataSubmitted:J({checkout:t,order:e})}}))),Ct=function(){var t=tI((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=tI((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,H.memoizeOne)((function(n){return void 0===n&&(n=aE),{getApplyError:t(n),isApplying:e(n)}}))}(),It=function(){var t=tI((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=tI((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,H.memoizeOne)((function(n){return void 0===n&&(n=GO),{getUpdateError:t(n),isUpdating:e(n)}}))}(),Pt=(Z=tI((function(t){return t.data}),(function(t){return function(){return t}})),X=tI((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),Q=tI((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,H.memoizeOne)((function(t){return void 0===t&&(t=zO),{getEmail:Z(t),getSendError:X(t),isSending:Q(t)}}))),Ot=function(){var t=tI((function(t){return t.data}),(function(t){return function(){return t}})),e=tI((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=tI((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=tI((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,H.memoizeOne)((function(o){return void 0===o&&(o=fP),{getExtensions:t(o),getExtensionByRegion:e(o),getLoadError:n(o),isLoading:r(o)}}))}();return function(t,e){void 0===e&&(e={});var n,r=$(t.billingAddress),o=tt(t.cart),i=et(t.checkoutButton),a=rt(t.countries),s=ot(t.coupons),c=it(t.customer),u=at(t.customerStrategies),l=Ot(t.extensions),d=ut(t.formFields),p=st(t.giftCertificates),h=ct(t.instruments),f=_t(t.orderBillingAddress),y=lt(t.paymentMethods),m=ht(t.paymentProviderCustomer),v=dt(t.paymentStrategies),g=pt(t.pickupOptions),b=ft(t.remoteCheckout),w=yt(t.consignments),_=mt(t.shippingCountries),S=vt(t.shippingStrategies),C=It(t.subscriptions),I=Ct(t.storeCredit),P=Pt(t.signInEmail),O=gt(t.consignments,o),E=bt(t.checkout,r,o,O,s,c,p),A=wt(t.order,f,s),k=St(E,A),T={billingAddress:r,cart:o,checkout:E,checkoutButton:i,config:nt(t.config,t.formFields),consignments:O,countries:a,coupons:s,customer:c,customerStrategies:u,extensions:l,form:d,giftCertificates:p,instruments:h,order:A,orderBillingAddress:f,payment:k,paymentMethods:y,paymentProviderCustomer:m,paymentStrategies:v,pickupOptions:g,remoteCheckout:b,shippingAddress:w,shippingCountries:_,shippingStrategies:S,signInEmail:P,subscriptions:C,storeCredit:I};return e.shouldWarnMutation?(n=T,Object.keys(n).reduce((function(t,e){return t[e]=tE(n[e]),t}),{})):T}}var uE=function(){return uE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([bE],t)}();const _E=function(){function t(t){this._checkoutButton=t.checkoutButton}return t.prototype.isInitializingButton=function(t){return this._checkoutButton.isInitializing(t)},t.prototype.isDeinitializingButton=function(t){return this._checkoutButton.isDeinitializing(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([bE],t)}();function SE(t){return{errors:new wE(t),statuses:new _E(t)}}var CE=function(){return CE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const PE=IE;var OE=function(){return OE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n55?55:t<25?25:t}function ME(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,s=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function zE(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var RE=function(){return RE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);i>3&&a&&Object.defineProperty(e,n,a)}([fr],t.prototype,"_handleWalletButtonClick",null),t}();var XE=function(){return XE=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"pending"}:{label:s,amount:"".concat(e.grandTotal.toFixed(l)),type:"final"}};if(f)null===(o=y.requiredShippingContactFields)||void 0===o||o.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:"".concat(e.subtotal.toFixed(l))}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:"".concat(t.amount.toFixed(l))})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return fA(r,void 0,void 0,(function(){var r;return yA(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=o.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw o.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return fA(r,void 0,void 0,(function(){return yA(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return fA(r,void 0,void 0,(function(){var t;return yA(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/".concat(e.id,"/signout"),[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Ne;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return fA(r,void 0,void 0,(function(){return yA(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return fA(this,void 0,void 0,(function(){var n,r;return yA(this,(function(o){switch(o.label){case 0:if(o.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new Nt(zt.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=o.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),new mi;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),o=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new Nt(zt.MissingPaymentMethod);var i=this._getBaseRequest(n,o,r,this._paymentMethod);delete i.total.type,t.completePaymentMethodSelection({newTotal:i.total,newLineItems:i.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return fA(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y;return yA(this,(function(m){switch(m.label){case 0:o=this._transformContactToAddress(n.shippingContact),m.label=1;case 1:return m.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(o)];case 2:return m.sent(),[3,4];case 3:throw m.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,s=i.getCheckoutOrThrow(),c=null===(r=s.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,u=s.consignments[0].availableShippingOptions,l=null==u?void 0:u.find((function(t){return t.id===c})),d=null==u?void 0:u.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:"".concat(l.cost.toFixed(a)),detail:l.additionalDescription,identifier:l.id}]:[],d&&mA(mA([],d.filter((function(t){return t.isRecommended})),!0),d.filter((function(t){return!t.isRecommended})),!0).forEach((function(t){return p.push({label:t.description,amount:"".concat(t.cost.toFixed(a)),detail:t.additionalDescription,identifier:t.id})})),!(u instanceof Array))throw new Error("Shipping options not available.");if(0===u.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:"".concat(s.grandTotal.toFixed(a))},[]),[2];h=u.find((function(t){return t.isRecommended})),f=h?h.id:u[0].id,y=l?l.id:f,m.label=5;case 5:return m.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return m.sent(),[3,8];case 7:throw m.sent(),new Error("Shipping options update failed");case 8:return i=this._paymentIntegrationService.getState(),s=i.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:"".concat(s.grandTotal.toFixed(a))},newLineItems:this._getUpdatedLineItems(s,a)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return fA(this,void 0,void 0,(function(){var r,o,i,a;return yA(this,(function(s){switch(s.label){case 0:r=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return s.sent(),[3,4];case 3:throw s.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return o=this._paymentIntegrationService.getState(),i=o.getCartOrThrow().currency.decimalPlaces,a=o.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:"".concat(a.grandTotal.toFixed(i))},newLineItems:this._getUpdatedLineItems(a,i)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:"".concat(t.subtotal.toFixed(e))}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:"".concat(t.amount.toFixed(e))})})),n.push({label:this._shippingLabel,amount:"".concat(t.shippingCostTotal.toFixed(e))}),n},t.prototype._updateShippingOption=function(t){return fA(this,void 0,void 0,(function(){return yA(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return fA(this,void 0,void 0,(function(){var n;return yA(this,(function(r){return n=["validationUrl=".concat(e.validationURL),"merchantIdentifier=".concat(t.initializationData.merchantId),"displayName=".concat(t.initializationData.storeName),"domainName=".concat(window.location.hostname)].join("&"),[2,this._requestSender.post((o=t.initializationData.paymentsUrl,"".concat(o,"/api/public/v1/payments/applepay/validate_merchant")),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var o}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){var r;return fA(this,void 0,void 0,(function(){var o,i,a,s,c,u,l,d,p,h,f,y,m;return yA(this,(function(v){switch(v.label){case 0:return o=t.payment,i=o.token,a=o.billingContact,s=o.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),l=u.lineItems.physicalItems.length>0,(null===(r=n.initializationData)||void 0===r?void 0:r.gateway)!==Fe.BRAINTREE?[3,2]:[4,this._getBraintreeDeviceData()];case 1:d=v.sent(),v.label=2;case 2:p={methodId:n.id,paymentData:{deviceSessionId:d,formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},h=this._transformContactToAddress(a),f=this._transformContactToAddress(s),y=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",v.label=3;case 3:return v.trys.push([3,9,,10]),[4,this._paymentIntegrationService.updateBillingAddress(hA(hA({},h),{email:y,phone:m}))];case 4:return v.sent(),l?[4,this._paymentIntegrationService.updateShippingAddress(f)]:[3,6];case 5:v.sent(),v.label=6;case 6:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 7:return v.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 8:return v.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 9:throw v.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 10:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t.prototype._getBraintreeDeviceData=function(){return fA(this,void 0,void 0,(function(){return yA(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this._braintreeSdk.getDataCollectorOrThrow()];case 1:return[2,t.sent().deviceData];case 2:return t.sent(),[3,3];case 3:return[2]}}))}))},t.prototype._initializeBraintreeSdk=function(){return fA(this,void 0,void 0,(function(){var t,e;return yA(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.loadPaymentMethod(Fe.BRAINTREE)];case 1:return n.sent(),t=this._paymentIntegrationService.getState(),(e=t.getPaymentMethod(Fe.BRAINTREE))&&e.clientToken&&e.initializationData?(this._braintreeSdk.initialize(e.clientToken),[2]):[2]}}))}))},t}();const gA=vA,bA=ie((function(t){var e=t.getState().getHost;return new gA((0,s.createRequestSender)({host:e()}),t,new Be,new Pe(new ze((0,c.getScriptLoader)(),window)))}),[{id:"applepay"}]);var wA=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return e=this,n=void 0,o=function(){var e,n,r,o,i,a,s,c,u,l,d,p,h;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]\n Tell Me More'),n=document.createElement("div");return n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",n.innerHTML=e,t.appendChild(n),n},t}();const EA=OA,AA=ie((function(t){var e=window,n=new Pe(new ze((0,c.getScriptLoader)(),e));return new EA(t,(0,mn.createFormPoster)(),n)}),[{id:"braintreevisacheckout"}]);function kA(t){var e=t.billingAddress,n=t.email,r=t.firstName,o=t.lastName,i=t.phone,a=t.shippingAddress,s=e||a;return{email:n,first_name:r,last_name:o,phone_number:i,address_line_1:null==s?void 0:s.line1,address_line_2:null==s?void 0:s.line2,city:null==s?void 0:s.city,state:null==s?void 0:s.state,country_code:null==s?void 0:s.countryCode,postal_code:null==s?void 0:s.postalCode}}function TA(t){var e=t.email,n=t.phone,r=t.shippingAddress,o=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:o[0]||"",last_name:o[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}var xA=function(){return xA=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(u=l.sent()))throw new Error(u);throw u;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return ek(this,void 0,void 0,(function(){var e,n,r;return nk(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return ek(this,void 0,void 0,(function(){var e,n;return nk(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t}();const ok=rk,ik=ie((function(t){return new ok(t,qi(t))}),[{id:"paypalcommerce"}]);var ak=function(){return ak=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return l.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:l.sent(),l.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return l.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return l.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:if("string"==typeof(u=l.sent()))throw new Error(u);throw u;case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return sk(this,void 0,void 0,(function(){var e,n,r;return ck(this,(function(o){switch(o.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.countryCode,postalCode:t.shippingAddress.postalCode,stateOrProvinceCode:t.shippingAddress.state}),o.label=1;case 1:return o.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return o.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return o.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return o.sent(),[3,7];case 6:if("string"==typeof(r=o.sent()))throw new Error(r);throw r;case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return sk(this,void 0,void 0,(function(){var e,n;return ck(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:if("string"==typeof(n=r.sent()))throw new Error(n);throw n;case 5:return[2]}}))}))},t.prototype.renderMessages=function(t,e,n){var r={amount:this.paymentIntegrationService.getState().getCheckoutOrThrow().outstandingBalance,placement:"cart",style:n?Wv(n):{layout:"text"}};t.Messages(r).render("#".concat(e))},t}();const lk=uk,dk=ie((function(t){return new lk(t,qi(t),pa())}),[{id:"paypalcommercecredit"}]);var pk=function(){return pk=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]6e5)&&t instanceof Vk&&t.subtype===qk.MissingContent?(this._storage.removeItem(Yk),this._storage.removeItem(Wk),this._allowCookie()):Promise.reject()},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const Jk=Kk;var Zk=function(){function t(t){this._options=t}return t.prototype.createFrame=function(t,e){var n=document.getElementById(e),r=(this._options||{}).timeout,o=void 0===r?6e4:r;if(!n)throw new Vk("Unable to embed the iframe because the container element could not be found.",qk.MissingContainer);var i=document.createElement("iframe");return i.src=t,i.style.border="none",i.style.display="none",i.style.width="100%",i.allowPaymentRequest=!0,i.allow="payment",n.appendChild(i),this._toResizableFrame(i,o).catch((function(t){throw n.removeChild(i),t}))},t.prototype._toResizableFrame=function(t,e){return new Promise((function(n,r){var o=window.setTimeout((function(){r(new Vk("Unable to embed the iframe because the content could not be loaded."))}),e),i=function(e){if((e.origin===Bs(t.src).origin||e.origin===Gs(Bs(t.src)).origin)&&(js(e.data,Bk.FrameError)&&(a(),r(new Vk(e.data.payload.message,qk.MissingContent))),js(e.data,Bk.FrameLoaded))){t.style.display="";var o=ud({scrolling:!1,sizeWidth:!1,heightCalculationMethod:e.data.payload&&e.data.payload.contentId?"taggedElement":"lowestElement"},t);a(),n(o[o.length-1])}},a=function(){window.removeEventListener("message",i),window.clearTimeout(o)};window.addEventListener("message",i)}))},t}();const Xk=Zk;var Qk="BigCommerce.EmbeddedCheckout";function $k(t){var e=Bs(t.url).origin;return new Jk(new Xk,new Hs(e),new qs(e),new Gh({styles:t.styles&&t.styles.loadingIndicator}),(0,s.createRequestSender)(),new Cw(Qk),window.location,t).attach()}function tT(t){if(t.payload&&t.payload.contentId){var e=document.getElementById(t.payload.contentId);e&&!e.hasAttribute("data-iframe-height")&&e.setAttribute("data-iframe-height","")}}function eT(t){return"object"==typeof t&&null!==t&&"message"in t&&"type"in t}var nT=function(){function t(t,e,n,r){void 0===r&&(r={}),this._messageListener=t,this._messagePoster=e,this._untargetedMessagePoster=n,this._messageHandlers=r,this._messageListener.listen()}return t.prototype.postComplete=function(){var t={type:Bk.CheckoutComplete};this._postMessage(t)},t.prototype.postError=function(t){var e={type:Bk.CheckoutError,payload:this._transformError(t)};this._postMessage(e)},t.prototype.postFrameError=function(t){var e={type:Bk.FrameError,payload:this._transformError(t)};this._postMessage(e,{untargeted:!0})},t.prototype.postFrameLoaded=function(t){var e={type:Bk.FrameLoaded,payload:t};this._postMessage(e)},t.prototype.postLoaded=function(){var t={type:Bk.CheckoutLoaded};this._postMessage(t)},t.prototype.postSignedOut=function(){var t={type:Bk.SignedOut};this._postMessage(t)},t.prototype.receiveStyles=function(t){this._messageListener.addListener(Hk.StyleConfigured,(function(e){var n=e.payload;t(n)}))},t.prototype._postMessage=function(t,e){if(this._notifyMessageHandlers(t),e&&e.untargeted)return this._untargetedMessagePoster.post(t);this._messagePoster.post(t)},t.prototype._notifyMessageHandlers=function(t){var e=this;Object.keys(this._messageHandlers).forEach((function(n){if(t.type===n){var r=e._messageHandlers[n];r&&r.call(null,t)}}))},t.prototype._transformError=function(t){return{message:t.message,type:eT(t)?t.type:void 0,subtype:eT(t)?t.subtype:void 0}},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const rT=nT;const oT=function(){function t(){}return t.prototype.postComplete=function(){},t.prototype.postError=function(){},t.prototype.postFrameError=function(){},t.prototype.postFrameLoaded=function(){},t.prototype.postLoaded=function(){},t.prototype.postSignedOut=function(){},t.prototype.receiveStyles=function(){},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();function iT(t){var e;n(405);var r=t.parentWindow||window.parent;return window===r?new oT:new rT(new Hs(t.parentOrigin),new qs(t.parentOrigin,r),new qs("*",r),((e={})[Bk.FrameLoaded]=tT,e))}const aT=require("intl-messageformat"),sT=require("messageformat");var cT=n.n(sT),uT="en",lT="optimized_checkout",dT=function(){function t(t,e){var n;this._logger=e;var r=this._transformConfig(t),o=r.locale,i=r.locales,a=r.translations;this._locale=o,this._locales=i,this._translations=a,this._formatters={},this._isCspNonceExperimentEnabled=null===(n=t.isCspNonceExperimentEnabled)||void 0===n||n}return t.prototype.mapKeys=function(t){var e=this;Object.keys(t).forEach((function(n){var r="".concat(lT,".").concat(t[n]);e._translations["".concat(lT,".").concat(n)]=e._translations[r]}))},t.prototype.getLocale=function(){return this._hasTranslations()?this._locale:uT},t.prototype.translate=function(t,e){var n;void 0===e&&(e={});var r="".concat(lT,".").concat(t);if("string"!=typeof this._translations[r])return this._logger.warn('Translation key "'.concat(r,'" is missing')),r;if(this._isCspNonceExperimentEnabled){this._formatters[r]||(this._formatters[r]=new aT.IntlMessageFormat(this._escapeSpecialCharacters(this._translations[r]||""),this._locales[r],void 0,{ignoreTag:!0}));try{return this._formatters[r].format(this._transformData(e))}catch(t){if(this._isFormatError(t))return null!==(n=t.originalMessage)&&void 0!==n?n:"";throw t}}if(!this._formatters[r]){var o=new(cT())(this._locales[r]);this._formatters[r]=o.compile(this._translations[r]||"")}return this._formatters[r](this._transformData(e))},t.prototype._transformConfig=function(t){void 0===t&&(t={});var e={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:t.locale||uT},n=t.locales||{},r=this._flattenObject(t.translations||{}),o=this._flattenObject(t.defaultTranslations||{}),i=this._flattenObject(t.fallbackTranslations||{});return(0,l.union)(Object.keys(i),Object.keys(o),Object.keys(r)).forEach((function(a){var s,c;r&&r[a]?(e.translations[a]=r[a],e.locales[a]=n[a]||e.locale):o[a]?(e.translations[a]=o[a],e.locales[a]=null!==(s=t.defaultLocale)&&void 0!==s?s:uT):(e.translations[a]=i[a],e.locales[a]=null!==(c=t.fallbackLocale)&&void 0!==c?c:uT)})),e},t.prototype._flattenObject=function(t,e,n){var r=this;void 0===e&&(e={}),void 0===n&&(n="");try{Object.keys(t).forEach((function(o){var i=t[o],a=n?"".concat(n,".").concat(o):o;if((0,l.isObject)(i))return r._flattenObject(i,e,a);e[a]=i}))}catch(t){this._logger.warn("Unable to parse object: ".concat(t))}return e},t.prototype._transformData=function(t){return Object.keys(t).reduce((function(e,n){var r=t[n];return e[n]=null==r?"":r,e}),{})},t.prototype._hasTranslations=function(){var t=this;return Object.keys(this._locales).map((function(e){return t._locales[e]})).filter((function(e){return e.split("-")[0]===t._locale.split("-")[0]})).length>0},t.prototype._isFormatError=function(t){return"object"==typeof t&&null!==t&&"originalMessage"in t},t.prototype._escapeSpecialCharacters=function(t){return t.replace(/(\w+)='([^']*)'/g,"$1=''$2''")},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();const pT=dT;function hT(t){return void 0===t&&(t={}),new pT(t,V())}const fT=function(){function t(t){this._storeConfig=t,this._customerFormatter=new vr(this._storeConfig.shopperCurrency),this._storeFormatter=new vr(this._storeConfig.currency)}return t.prototype.toCustomerCurrency=function(t){var e=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(t*e)},t.prototype.toStoreCurrency=function(t){return this._storeFormatter.format(t)},function(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}([fr],t)}();function yT(t){return new fT(t)}var mT=function(){return mT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=8096}function _T(t){return Object.keys(t).reduce((function(e,n){var r=typeof t[n];return"string"===r||"number"===r?vT(vT([],e,!0),["".concat(n,"=").concat(t[n])],!1):"object"===r&&null!==t[n]?vT(vT([],e,!0),[_T(t[n])],!1):e}),[]).join("&")}var ST,CT=function(){return CT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?"1":"0",apm_list:t.join(",")})},t.prototype._getApmSelectedEventOptions=function(t,e){var n=(this.checkoutService.getState().data.getPaymentMethods()||[]).map((function(t){return t.id}));return xT(xT({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:t,apm_location:e?"pre-email section":"payment section"})},t.prototype._getOrderPlacedEventOptions=function(t){var e=this.checkoutService.getState().data.getCart();return xT(xT({},this._getEventCommonOptions()),{selected_payment_method:t,currency_code:(null==e?void 0:e.currency.code)||""})},t}();const MT=DT;function zT(t){return new MT(t)}var RT=function(){return RT=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?"1":"0",apm_list:t.join(",")})},t.prototype._getApmSelectedEventOptions=function(t,e){var n=(this._checkoutService.getState().data.getPaymentMethods()||[]).map((function(t){return t.id}));return RT(RT({},this._getEventCommonOptions()),{apm_shown:n.length>1?"1":"0",apm_list:n.join(","),apm_selected:t,apm_location:e?"pre-email section":"payment section"})},t.prototype._getOrderPlacedEventOptions=function(t){var e=this._checkoutService.getState().data.getCart();return RT(RT({},this._getEventCommonOptions()),{selected_payment_method:t,currency_code:(null==e?void 0:e.currency.code)||""})},t}();const FT=NT;function LT(t){return new FT(t)}var BT=function(){function t(t,e){this._host=t,this._hostedFormFactory=e}return t.prototype.submitStoredCard=function(t,e){return n=this,r=void 0,i=function(){var n;return function(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?t.salePrice:t.listPrice,sku:t.sku,variant_id:t.variantId,discount:t.discountAmount,coupon_amount:t.couponAmount,brand_name:t.brand,currency:e,category_names:(n=t,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?(0,l.flatten)(n.categories).map((function(t){return t.name})):[]),retail_price:t.retailPrice}}));return HT(HT(HT([],n,!0),o,!0),r,!0).map((function(t){return VT(VT({},t),{product_id:String(t.product_id)})}))},t.prototype._hasStepCompleted=function(t){return this._completedSteps[t]},t}();const YT=WT,KT=function(){function t(){}return t.prototype.checkoutBegin=function(){},t.prototype.orderPurchased=function(){},t.prototype.stepCompleted=function(){},t.prototype.customerEmailEntry=function(){},t.prototype.customerSuggestionInit=function(){},t.prototype.customerSuggestionExecute=function(){},t.prototype.customerPaymentMethodExecuted=function(){},t.prototype.showShippingMethods=function(){},t.prototype.selectedPaymentMethod=function(){},t.prototype.clickPayButton=function(){},t.prototype.paymentRejected=function(){},t.prototype.paymentComplete=function(){},t.prototype.exitCheckout=function(){},t}();function JT(t){return function(t){return"bodlEvents"in t}(window)?new YT(t,window.bodlEvents.checkout):new KT}module.exports=r})(); //# sourceMappingURL=checkout-sdk.js.map \ No newline at end of file diff --git a/dist/checkout-sdk.js.map b/dist/checkout-sdk.js.map index 6a3096429a..1a069b0176 100644 --- a/dist/checkout-sdk.js.map +++ b/dist/checkout-sdk.js.map @@ -1 +1 @@ -{"version":3,"file":"checkout-sdk.js","mappings":"kCAAAA,EAAOC,QAAUC,QAAQ,iB,UCAzBF,EAAOC,QAAUC,QAAQ,gD,GCCrBC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EA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E,EACA9vE,EACAJ,EACAsC,GAA4CxwD,EAAcsxB,GAC1D,IAAI,GAAyBtxB,GARjC,IAYRqkC,EAASnuC,SACL,GAAoBqoI,UACpB,WACI,WAAI,GACA3yI,EACAsiE,EACAI,EACAL,EACAI,EACA,IAAI,GAAoBruD,GACxBmjB,EAPJ,IAWRkhB,EAASnuC,SACL,GAAoBsoI,UACpB,WACI,WAAI,GACA5yI,EACAsiE,EACAI,EACAL,EACA32C,EALJ,IASR+sB,EAASnuC,SACL,GAAoBuoI,KACpB,WACI,WAAI,GACA7yI,EACAsiE,EACAI,EACAL,EACA,IAAI,GACAriE,EACA0iE,EACA,IAAI,GAAe,IAAI,GAAqBtuD,KARpD,IAaRqkC,EAASnuC,SACL,GAAoBwoI,YACpB,WACI,WAAI,GACA9yI,EACAsiE,EACAI,EACA,IAAI,GAAuBtuD,GAC3BmjB,EALJ,IASRkhB,EAASnuC,SACL,GAAoByoI,KACpB,WACI,WAAI,GACA/yI,EACAsiE,EACAG,EACA46C,EACA36C,EACA,IAAI,GAAgBtuD,GANxB,IAURqkC,EAASnuC,SACL,GAAoB0oI,gBACpB,WACI,WAAI,GACAhzI,EACAsiE,EACA,IAAI,GAAmBluD,GAH3B,IAORqkC,EAASnuC,SACL,GAAoB2oI,uBACpB,WACI,WAAI,GACAjzI,EACAsiE,EACA,IAAI,GAAmBluD,GAH3B,IAORqkC,EAASnuC,SACL,GAAoBo0G,OACpB,WACI,WAAIw0B,GACAlzI,EACAsiE,EACAypD,GACI/rH,EACAsiE,EACA58B,EACAsmF,EACA3pD,GAEJ,IAAI8wE,GAAeztG,EAAesmF,GAClC,IAAI,GAAe,SAXvB,IAeRvzE,EAASnuC,SACL,GAAoB8oI,QACpB,WACI,WAAI,GACApzI,EACAsiE,EACAI,EACAL,EACA,IAAI,GAAgBjuD,GALxB,IASDqkC,CACX,CPzHY,CACIz4C,GACA+uD,GACArpB,GACAo9B,GACAvrC,IAEJo2G,GACArrE,GACAU,IAEJ,IAAI,G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YrvH,OAAOzqB,EAAK85I,aAFlB,GAKlB,EAEQ,YAAA4E,kBAAR,SAA0B/1F,GACtB,OAAO/zD,KAAKmjJ,gBAAgBpvF,EAChC,EACJ,EApRA,G,eCbA,wBA0BA,QAzBI,YAAAi1F,cAAA,WAAuB,EAEvB,YAAAG,eAAA,WAAwB,EAExB,YAAAS,cAAA,WAAuB,EAEvB,YAAAI,mBAAA,WAA4B,EAE5B,YAAAE,uBAAA,WAAgC,EAEhC,YAAAC,0BAAA,WAAmC,EAEnC,YAAAxE,8BAAA,WAAuC,EAEvC,YAAAyE,oBAAA,WAA6B,EAE7B,YAAApE,sBAAA,WAA+B,EAE/B,YAAAwE,eAAA,WAAwB,EAExB,YAAAC,gBAAA,WAAyB,EAEzB,YAAA3E,gBAAA,WAAyB,EAEzB,YAAA4E,aAAA,WAAsB,EAC1B,EA1BA,GCmBe,SAASmB,GACpB5oJ,GAEA,OCtBG,SAAuB6P,GAC1B,MAAO,eAAgBA,CAC3B,CDoBQg5I,CAAch5I,QACP,IAAI,GAAmB7P,EAAW6P,OAAO81I,WAAWjqJ,UAGxD,IAAI,EACf,C","sources":["webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/compat get default export","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/webpack/runtime/make namespace object","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/request-sender\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/script-loader\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/data-store\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"lodash\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs/operators\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/create-data-store-projection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/get-environment.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/console-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/noop-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/get-default-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/create-logger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/memoize\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cachable-action-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/is-action-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cache-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/errors/checkout-not-available-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-default-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-params.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/is-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/resolve-id-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/getShippableItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/getLineItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/util-types/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/isInternalCheckoutSelectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/create-amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/to-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/form-poster\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@braintree/browser-detection\"","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/paypal.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"local-storage-fallback\"","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/create-braintree-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/currency-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/items-require-shipping.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-card-network-key.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-error-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-initialize-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-key.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-additional-action-processable.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/create-google-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-adyenv2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-adyenv3-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-authorizenet-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-authorizenet-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-authorizenet-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/is-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-checkoutcom-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-checkoutcom-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-threedsecure-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-checkoutcom-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-cybersource-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-cybersource-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-bnz-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-orbital-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-orbital-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/google-pay-stripe-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripeupe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-worldpayaccess-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-worldpayaccess-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-braintree-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-braintree-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-braintree-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-paypal-commerce-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-tdonlinemart-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-td-online-mart-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-tdonlinemart-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/create-paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/create-paypal-commerce-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/create-paypal-commerce-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/paypal-commerce-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/create-paypal-commerce-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-upe-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-or-merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/apple-pay/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-comparator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-changed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/is-iframe-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/payment-human-verification-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/create-spam-protection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-payment-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-value-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/hosted-input-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-order-data-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-tax-provider-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/bigpay-client\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/map-to-internal-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-coupon.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-gift-certificate.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/generated/checkout-button-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-items.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-gift-certificate-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-cart.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/promotion/map-to-discount-notifications.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/map-to-internal-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-expiry-formatter.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"card-validator\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-number-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/map-to-internal-order.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/map-to-internal-shipping-option.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/errors/update-subscriptions-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-plain-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/clone-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/default-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/payment-integration-store-projection-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-sdk-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/visacheckout-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-visacheckout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/get-callback-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/masterpass/masterpass-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/square/square-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-event-broadcaster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/subscribers/subscribe-consignments-change.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-card-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-account-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/create-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-boleto-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/create-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirmJs.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/create-affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/afterpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/is-afterpay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/create-afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/isAmazonPayAdditionalActionError.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-3ds.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-hosted-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-hosted-stored-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-input-validation-error-description.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-hosted-input-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-name-on-card-input.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-array-of-allowed-props.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/create-bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm/bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-provider-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm/create-bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnapv2/bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnapv2/create-bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/analytics-extra-items-manager.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/is-analytics-step-tracker-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-with-account-creation.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/is-bolt-payment-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-us-bank-account-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-ach/braintree-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-ach/create-braintree-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/create-braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-paypal-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/create-braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/create-braintree-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-custom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/create-checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/isThreeDSecureRequiredError.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/create-checkoutcom-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/create-checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-ideal/checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-ideal/create-checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-apm/checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-apm/create-checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/clearpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/create-clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/create-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-three-d-secure-flow.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersource/cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersource/create-cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-credit-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersourcev2/cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersourcev2/create-cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/create-digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/create-external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-additional-action-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-adyenv2-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-adyenv3-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-authorizenet-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-checkoutcom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-orbital-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-braintree-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-tdonlinemart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-execute-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/humm-integration/src/humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/humm-integration/src/create-humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarna-supported-countries.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/klarna-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/create-klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-token-updater.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/create-klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/create-legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/mollie-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/is-mollie-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/create-mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/moneris-integration/src/moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/moneris-integration/src/create-moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/no-payment-data-required-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/create-no-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/create-offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/create-offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-commerce-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-vaulted-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-commerce-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/create-paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-ratepay/paypal-commerce-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-ratepay/create-paypal-commerce-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/paypal-commerce-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/create-paypal-commerce-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-pro-integration/src/paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-pro-integration/src/create-paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sagepay-integration/src/sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sagepay-integration/src/create-sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/create-sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/enums.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/is-squarev2-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/create-squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/is-individual-card-element-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/create-stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/isTdOnlineMartAdditionalAction.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/is-create-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/create-td-online-mart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/storefront-payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/zip-integration/src/zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/zip-integration/src/create-zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/storage/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/barclays/barclays-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bnz/bnz-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-credit-card-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-credit-card-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-declined-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-library.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-express-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"query-string\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/RedirectionState.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/continue-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/redirect.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/human-verification/human-verification.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/success.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/failure.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/create-step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-completed-payments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/get-ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/card.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/none.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/card-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/none-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-risk-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-response-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-paypal-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-bank-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/amazon-pay-v2/amazon-pay-v2-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/braintree/braintree-fastlane-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/default/default-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/paypal-commerce/paypal-commerce-fastlane-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/stripe-upe/stripe-upe-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-message-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/to-single-line.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service-error-transformer.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"reselect\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/with-memoized-combiner.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-selector.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"shallowequal\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-shallow-equal-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unrecoverable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-internal-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-storefront-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/omit-deep.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/clear-error-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/array-replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-merge.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/merge-or-push.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-flatten.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-with-sorted-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/create-freeze-proxy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/supported-payment-instruments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/is-address-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-internal-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-event-broadcaster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-maps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-resolver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/selector-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-private.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/is-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/masterpass/masterpass-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/errors/amazon-pay-v2-config-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/isWithBuyNowFeatures.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/isUnsupportedBrowserError.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-braintree-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-adyenv2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-adyenv3-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-authorizenet-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-checkoutcom-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-cybersource-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-orbital-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-worldpayaccess-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-tdonlinemart-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/invalid-login-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/not-embeddable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/embedded-content-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embed-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/handle-frame-loaded-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/iframe-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/noop-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/create-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"intl-messageformat\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"messageformat\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/create-language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-tracker-ga.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/noop-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/create-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-fastlane-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/braintree-analytic-tracker/braintree-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/braintree-analytic-tracker/create-braintree-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/paypal-commerce-analytic-tracker/paypal-commerce-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/paypal-commerce-analytic-tracker/create-paypal-commerce-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/stored-card-hosted-form-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/create-hosted-form-stored-card-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/analytics-steps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/bodl-emitter-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/noop-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/create-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/is-bodl-enabled.ts"],"sourcesContent":["module.exports = require(\"iframe-resizer\");","module.exports = require(\"iframe-resizer/js/iframeResizer.contentWindow\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/request-sender\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/script-loader\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/data-store\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"lodash\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs/operators\");","import { Action, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, Observable, of, throwError } from 'rxjs';\n\nexport default function throwErrorAction(\n type: TType,\n error?: TPayload,\n meta?: TMeta,\n): Observable> {\n if (isErrorAction(error)) {\n return concat(of(error), throwError(createErrorAction(type, error.payload, meta)));\n }\n\n return throwError(createErrorAction(type, error, meta));\n}\n\nfunction isErrorAction(action: any): action is Action {\n return action && action.type && action.error;\n}\n","import { setPrototypeOf } from '../../utility';\n\nimport CustomError from './custom-error';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentProviderCustomer,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingPaymentProviderCustomer:\n return 'Unable to proceed because payment provider customer is unavailable.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum BillingAddressActionType {\n UpdateBillingAddressRequested = 'UPDATE_BILLING_ADDRESS_REQUESTED',\n UpdateBillingAddressSucceeded = 'UPDATE_BILLING_ADDRESS_SUCCEEDED',\n UpdateBillingAddressFailed = 'UPDATE_BILLING_ADDRESS_FAILED',\n\n ContinueAsGuestRequested = 'CONTINUE_AS_GUEST_REQUESTED',\n ContinueAsGuestSucceeded = 'CONTINUE_AS_GUEST_SUCCEEDED',\n ContinueAsGuestFailed = 'CONTINUE_AS_GUEST_FAILED',\n}\n\nexport type BillingAddressAction = ContinueAsGuestAction | UpdateBillingAddressAction;\n\nexport type UpdateBillingAddressAction =\n | UpdateBillingAddressRequested\n | UpdateBillingAddressSucceeded\n | UpdateBillingAddressFailed;\n\nexport type ContinueAsGuestAction =\n | ContinueAsGuestRequested\n | ContinueAsGuestSucceeded\n | ContinueAsGuestFailed;\n\nexport interface UpdateBillingAddressRequested extends Action {\n type: BillingAddressActionType.UpdateBillingAddressRequested;\n}\n\nexport interface UpdateBillingAddressSucceeded extends Action {\n type: BillingAddressActionType.UpdateBillingAddressSucceeded;\n}\n\nexport interface UpdateBillingAddressFailed extends Action {\n type: BillingAddressActionType.UpdateBillingAddressFailed;\n}\n\nexport interface ContinueAsGuestRequested extends Action {\n type: BillingAddressActionType.ContinueAsGuestRequested;\n}\n\nexport interface ContinueAsGuestSucceeded extends Action {\n type: BillingAddressActionType.ContinueAsGuestSucceeded;\n}\n\nexport interface ContinueAsGuestFailed extends Action {\n type: BillingAddressActionType.ContinueAsGuestFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class UnableToContinueAsGuestError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to continue as a guest because the customer is already signed in.',\n );\n\n this.name = 'UnableToContinueAsGuestError';\n this.type = 'unable_to_continue_as_guest';\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Response } from '@bigcommerce/request-sender';\nimport { isEmpty } from 'lodash';\nimport { concat, defer, empty, merge, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { Checkout, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { GuestCredentials } from '../customer';\nimport { SubscriptionsActionCreator, UpdateSubscriptionsAction } from '../subscription';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\nimport {\n BillingAddressActionType,\n ContinueAsGuestAction,\n UpdateBillingAddressAction,\n} from './billing-address-actions';\nimport { UnableToContinueAsGuestError } from './errors';\n\nimport { BillingAddressRequestSender } from '.';\n\nexport default class BillingAddressActionCreator {\n constructor(\n private _requestSender: BillingAddressRequestSender,\n private _subscriptionActionCreator: SubscriptionsActionCreator,\n ) {}\n\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const isBillingFixExperimentEnabled =\n state.config.getConfig()?.storeConfig.checkoutSettings.features[\n 'CHECKOUT-8392.fix_billing_creation_in_checkout'\n ] ?? true;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const customer = state.customer.getCustomer();\n\n if (customer && !customer.isGuest) {\n throw new UnableToContinueAsGuestError();\n }\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n let billingAddressRequestBody: Partial;\n\n if (!billingAddress) {\n billingAddressRequestBody = credentials;\n } else {\n const { country, ...existingBillingAddressRequestBody } = billingAddress;\n\n billingAddressRequestBody = {\n ...existingBillingAddressRequestBody,\n ...credentials,\n };\n }\n\n const hasBillingAddress = !isEmpty(billingAddress);\n\n return merge(\n concat(\n of(createAction(BillingAddressActionType.ContinueAsGuestRequested)),\n defer(async () => {\n const { body } = await this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n isBillingFixExperimentEnabled,\n hasBillingAddress,\n options,\n );\n\n return createAction(\n BillingAddressActionType.ContinueAsGuestSucceeded,\n body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(BillingAddressActionType.ContinueAsGuestFailed, error),\n ),\n ),\n this._updateCustomerConsent(credentials, options),\n );\n };\n }\n\n updateAddress(\n address: Partial,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const isBillingFixExperimentEnabled =\n state.config.getConfig()?.storeConfig.checkoutSettings.features[\n 'CHECKOUT-8392.fix_billing_creation_in_checkout'\n ] ?? true;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(BillingAddressActionType.UpdateBillingAddressRequested));\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n const hasBillingAddress = !isEmpty(billingAddress);\n\n // If email is not present in the address provided by the client, then\n // fall back to the stored email as it could have been set separately\n // using a convenience method. We can't rely on billingAddress having\n // an ID to consider that there's a preexisting email, as billingAddress\n // object from Order doesn't have an ID.\n const billingAddressRequestBody = {\n ...address,\n email:\n typeof address.email === 'undefined' && billingAddress\n ? billingAddress.email\n : address.email,\n };\n\n if (billingAddress && billingAddress.id) {\n billingAddressRequestBody.id = billingAddress.id;\n }\n\n this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n isBillingFixExperimentEnabled,\n hasBillingAddress,\n options,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n BillingAddressActionType.UpdateBillingAddressSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n BillingAddressActionType.UpdateBillingAddressFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _updateCustomerConsent(\n { email, acceptsAbandonedCartEmails, acceptsMarketingNewsletter }: GuestCredentials,\n options?: RequestOptions,\n ): Observable {\n if (\n (acceptsAbandonedCartEmails === undefined || acceptsAbandonedCartEmails === null) &&\n (acceptsMarketingNewsletter === undefined || acceptsMarketingNewsletter === null)\n ) {\n return empty();\n }\n\n return this._subscriptionActionCreator.updateSubscriptions(\n {\n email,\n acceptsMarketingNewsletter: acceptsMarketingNewsletter || false,\n acceptsAbandonedCartEmails: acceptsAbandonedCartEmails || false,\n },\n options,\n );\n }\n\n private _createOrUpdateBillingAddress(\n checkoutId: string,\n address: Partial,\n isBillingFixExperimentEnabled: boolean,\n hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (isBillingFixExperimentEnabled) {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n\n if (!address.id) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\n\nconst DEFAULT_PARAMS = {\n include: [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n ].join(','),\n};\n\nexport default class BillingAddressRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n });\n }\n\n updateAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = address;\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, { params: DEFAULT_PARAMS, body, headers, timeout });\n }\n}\n","import { Action, createAction, createDataStore, ReadableDataStore } from '@bigcommerce/data-store';\n\nenum ProjectionActionType {\n Synchronize = 'SYNCHRONIZE',\n}\n\ninterface SynchronizeAction extends Action {\n type: ProjectionActionType.Synchronize;\n payload: TState;\n}\n\nexport interface DataStoreProjection\n extends ReadableDataStore {\n notifyState(): void;\n}\n\nexport default function createDataStoreProjection(\n store: ReadableDataStore,\n stateTransformer: (state: TState) => TTransformedState,\n): DataStoreProjection {\n const projection = createDataStore<\n TState | undefined,\n SynchronizeAction,\n TTransformedState\n >(\n (state, action) =>\n action.type === ProjectionActionType.Synchronize ? action.payload : state,\n store.getState(),\n { stateTransformer },\n );\n\n store.subscribe(\n (state) => {\n projection.dispatch(\n createAction(ProjectionActionType.Synchronize, state) as SynchronizeAction,\n );\n },\n { initial: false },\n );\n\n return projection;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ErrorActionType {\n ClearError = 'CLEAR_ERROR',\n}\n\nexport type ErrorAction = ClearErrorAction;\n\nexport interface ClearErrorAction extends Action {\n type: ErrorActionType.ClearError;\n payload: Error;\n}\n","import { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default class ErrorActionCreator {\n clearError(error: Error): ClearErrorAction {\n return {\n type: ErrorActionType.ClearError,\n payload: error,\n };\n }\n}\n","export default function getEnvironment(): string {\n try {\n return process.env.NODE_ENV || 'development';\n } catch (e) {\n return 'development';\n }\n}\n","import Logger from './logger';\n\ntype keys = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\nexport default class ConsoleLogger implements Logger {\n constructor(private _console?: Console) {}\n\n log(...messages: any[]): void {\n this._logToConsole('log', ...messages);\n }\n\n info(...messages: any[]): void {\n this._logToConsole('info', ...messages);\n }\n\n warn(...messages: any[]): void {\n this._logToConsole('warn', ...messages);\n }\n\n error(...messages: any[]): void {\n this._logToConsole('error', ...messages);\n }\n\n debug(...messages: any[]): void {\n this._logToConsole('debug', ...messages);\n }\n\n private _logToConsole(type: keys, ...messages: any[]): void {\n if (!this._console || !this._console[type]) {\n return;\n }\n\n this._console[type].call(this._console, ...messages);\n }\n}\n","import Logger from './logger';\n\nexport default class NoopLogger implements Logger {\n log(): void {}\n\n info(): void {}\n\n warn(): void {}\n\n error(): void {}\n\n debug(): void {}\n}\n","import { getEnvironment } from '../utility';\n\nimport createLogger from './create-logger';\nimport Logger from './logger';\n\nconst logger = createLogger(getEnvironment() !== 'test');\n\nexport default function getDefaultLogger(): Logger {\n return logger;\n}\n","import ConsoleLogger from './console-logger';\nimport Logger from './logger';\nimport NoopLogger from './noop-logger';\n\nexport default function createLogger(isEnabled = true): Logger {\n if (!isEnabled) {\n return new NoopLogger();\n }\n\n return new ConsoleLogger(console);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/memoize\");","import { Action } from '@bigcommerce/data-store';\n\nimport Config from './config';\n\nexport enum ConfigActionType {\n LoadConfigRequested = 'LOAD_CONFIG_REQUESTED',\n LoadConfigSucceeded = 'LOAD_CONFIG_SUCCEEDED',\n LoadConfigFailed = 'LOAD_CONFIG_FAILED',\n}\n\nexport type LoadConfigAction =\n | LoadConfigRequestedAction\n | LoadConfigSucceededAction\n | LoadConfigFailedAction;\n\nexport interface LoadConfigRequestedAction extends Action {\n type: ConfigActionType.LoadConfigRequested;\n}\n\nexport interface LoadConfigSucceededAction extends Action {\n type: ConfigActionType.LoadConfigSucceeded;\n}\n\nexport interface LoadConfigFailedAction extends Action {\n type: ConfigActionType.LoadConfigFailed;\n}\n","import cacheAction from './cache-action';\nimport isActionOptions from './is-action-options';\n\nexport default function cachableActionDecorator any>(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n const memoizedMethods = new WeakMap();\n\n function decorateMethod(this: object, method: TMethod): TMethod {\n return ((...args: any[]) => {\n const lastArg = args[args.length - 1];\n const { useCache } = isActionOptions(lastArg) ? lastArg : { useCache: false };\n\n if (!useCache) {\n return method.call(this, ...args);\n }\n\n const instanceMethods = memoizedMethods.get(this) || {};\n\n if (!memoizedMethods.get(this)) {\n memoizedMethods.set(this, instanceMethods);\n }\n\n if (!instanceMethods[key]) {\n instanceMethods[key] = cacheAction(method);\n }\n\n return instanceMethods[key].call(this, ...args);\n }) as TMethod;\n }\n\n return {\n get() {\n if (typeof descriptor.value !== 'function') {\n throw new Error('Decorator should be used in functions');\n }\n\n const value = decorateMethod.call(this, descriptor.value);\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n };\n}\n","import ActionOptions from './action-options';\n\nexport default function isActionOptions(param: any): param is ActionOptions {\n return param && typeof param.useCache === 'boolean';\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { memoize } from '@bigcommerce/memoize';\nimport { isEqual } from 'lodash';\nimport { from, Observable } from 'rxjs';\nimport { shareReplay } from 'rxjs/operators';\n\nexport default function cacheAction(fn: TFunction): TFunction {\n function decoratedFn(this: any, ...args: any[]) {\n const action = fn.call(this, ...args);\n\n if (action instanceof Observable) {\n return from(action).pipe(shareReplay());\n }\n\n if (typeof action === 'function') {\n return memoize((store) => from(action(store)).pipe(shareReplay()), { isEqual });\n }\n\n return action;\n }\n\n return memoize(decoratedFn as TFunction, { isEqual });\n}\n\ntype CreateActionFn = (...args: any[]) => Observable | ThunkAction | Action;\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\n\nimport { ConfigRequestSender } from '.';\n\nexport default class ConfigActionCreator {\n constructor(private _configRequestSender: ConfigRequestSender) {}\n\n @cachableAction\n loadConfig(options?: RequestOptions & ActionOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ConfigActionType.LoadConfigRequested));\n\n this._configRequestSender\n .loadConfig(options)\n .then((response) => {\n observer.next(\n createAction(ConfigActionType.LoadConfigSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(ConfigActionType.LoadConfigFailed, response));\n });\n });\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error when we are unable to retrieve a checkout object from the\n * server using the provided ID. It could be because the shopper does not have\n * permission to view the object, or the ID itself is invalid.\n */\nexport default class CheckoutNotAvailableError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'CheckoutNotAvailableError';\n this.type = 'checkout_not_available';\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutNotAvailableError } from '../checkout/errors';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Config from './config';\n\nexport default class ConfigRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadConfig({ timeout, params }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/checkout-settings';\n\n return this._requestSender\n .get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum CouponActionType {\n ApplyCouponRequested = 'APPLY_COUPON_REQUESTED',\n ApplyCouponSucceeded = 'APPLY_COUPON_SUCCEEDED',\n ApplyCouponFailed = 'APPLY_COUPON_FAILED',\n\n RemoveCouponRequested = 'REMOVE_COUPON_REQUESTED',\n RemoveCouponSucceeded = 'REMOVE_COUPON_SUCCEEDED',\n RemoveCouponFailed = 'REMOVE_COUPON_FAILED',\n}\n\nexport type CouponAction = ApplyCouponAction | RemoveCouponAction;\n\nexport type ApplyCouponAction =\n | ApplyCouponRequestedAction\n | ApplyCouponSucceededAction\n | ApplyCouponFailedAction;\n\nexport type RemoveCouponAction =\n | RemoveCouponRequestedAction\n | RemoveCouponSucceededAction\n | RemoveCouponFailedAction;\n\nexport interface ApplyCouponRequestedAction extends Action {\n type: CouponActionType.ApplyCouponRequested;\n}\n\nexport interface ApplyCouponSucceededAction extends Action {\n type: CouponActionType.ApplyCouponSucceeded;\n}\n\nexport interface ApplyCouponFailedAction extends Action> {\n type: CouponActionType.ApplyCouponFailed;\n}\n\nexport interface RemoveCouponRequestedAction extends Action {\n type: CouponActionType.RemoveCouponRequested;\n}\n\nexport interface RemoveCouponSucceededAction extends Action {\n type: CouponActionType.RemoveCouponSucceeded;\n}\n\nexport interface RemoveCouponFailedAction extends Action {\n type: CouponActionType.RemoveCouponFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyCouponAction,\n CouponAction,\n CouponActionType,\n RemoveCouponAction,\n} from './coupon-actions';\nimport CouponRequestSender from './coupon-request-sender';\n\nexport default class CouponActionCreator {\n constructor(private _couponRequestSender: CouponRequestSender) {}\n\n applyCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.ApplyCouponRequested));\n\n this._couponRequestSender\n .applyCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.ApplyCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.ApplyCouponFailed, response),\n );\n });\n });\n }\n\n removeCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.RemoveCouponRequested));\n\n this._couponRequestSender\n .removeCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.RemoveCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.RemoveCouponFailed, response),\n );\n });\n });\n }\n}\n","const CHECKOUT_DEFAULT_INCLUDES = [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'customer.customerGroup',\n 'payments',\n 'promotions.banners',\n];\n\nexport default CHECKOUT_DEFAULT_INCLUDES;\n","export enum CheckoutIncludes {\n AvailableShippingOptions = 'consignments.availableShippingOptions',\n PhysicalItemsCategoryNames = 'cart.lineItems.physicalItems.categoryNames',\n DigitalItemsCategoryNames = 'cart.lineItems.digitalItems.categoryNames',\n}\n\nexport default interface CheckoutParams {\n include?: CheckoutIncludes[] | CheckoutIncludeParam;\n}\n\nexport type CheckoutIncludeParam = {\n [key in CheckoutIncludes]?: boolean;\n};\n","import { uniq } from 'lodash';\n\nexport default function joinIncludes(includes: T[]): string {\n return uniq(includes).join(',');\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES, CheckoutIncludes } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class CouponRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n body: { couponCode },\n });\n }\n\n removeCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons/${couponCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum GiftCertificateActionType {\n ApplyGiftCertificateRequested = 'APPLY_GIFT_CERTIFICATE_REQUESTED',\n ApplyGiftCertificateSucceeded = 'APPLY_GIFT_CERTIFICATE_SUCCEEDED',\n ApplyGiftCertificateFailed = 'APPLY_GIFT_CERTIFICATE_FAILED',\n\n RemoveGiftCertificateRequested = 'REMOVE_GIFT_CERTIFICATE_REQUESTED',\n RemoveGiftCertificateSucceeded = 'REMOVE_GIFT_CERTIFICATE_SUCCEEDED',\n RemoveGiftCertificateFailed = 'REMOVE_GIFT_CERTIFICATE_FAILED',\n}\n\nexport type GiftCertificateAction = ApplyGiftCertificateAction | RemoveGiftCertificateAction;\n\nexport type ApplyGiftCertificateAction =\n | ApplyGiftCertificateRequestedAction\n | ApplyGiftCertificateSucceededAction\n | ApplyGiftCertificateFailedAction;\n\nexport type RemoveGiftCertificateAction =\n | RemoveGiftCertificateRequestedAction\n | RemoveGiftCertificateSucceededAction\n | RemoveGiftCertificateFailedAction;\n\nexport interface ApplyGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateRequested;\n}\n\nexport interface ApplyGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateSucceeded;\n}\n\nexport interface ApplyGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.ApplyGiftCertificateFailed;\n}\n\nexport interface RemoveGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateRequested;\n}\n\nexport interface RemoveGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateSucceeded;\n}\n\nexport interface RemoveGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.RemoveGiftCertificateFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyGiftCertificateAction,\n GiftCertificateActionType,\n RemoveGiftCertificateAction,\n} from './gift-certificate-actions';\n\nimport { GiftCertificateRequestSender } from '.';\n\nexport default class GiftCertificateActionCreator {\n constructor(private _giftCertificateRequestSender: GiftCertificateRequestSender) {}\n\n applyGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.ApplyGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .applyGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.ApplyGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.ApplyGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n\n removeGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.RemoveGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .removeGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.RemoveGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.RemoveGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class GiftCertificateRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n });\n }\n\n removeGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates/${giftCertificateCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return 'resolveIds' in module;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Factory from './factory';\n\nexport default class Registry {\n private _factories: { [key: string]: Factory };\n private _instances: { [key: string]: T };\n private _defaultToken: string;\n private _useFallback: string | boolean;\n private _tokenResolver: (token: string, registeredTokens: string[]) => string | undefined;\n\n constructor(options?: RegistryOptions) {\n this._factories = {};\n this._instances = {};\n this._defaultToken = options?.defaultToken ?? 'default';\n this._useFallback = options?.useFallback ?? true;\n this._tokenResolver = options?.tokenResolver ?? ((token) => token);\n }\n\n get(token?: K, cacheToken?: string): T {\n try {\n return this._getInstance(\n token || this._defaultToken,\n cacheToken || token || this._defaultToken,\n );\n } catch (error) {\n if (!this._useFallback) {\n throw error;\n }\n\n return this._getInstance(this._defaultToken, cacheToken || this._defaultToken);\n }\n }\n\n register(token: K, factory: Factory): void {\n if (this._hasFactory(token)) {\n throw new InvalidArgumentError(`'${token}' is already registered.`);\n }\n\n this._factories[token] = factory;\n }\n\n protected _hasFactory(token: string): boolean {\n return !!this._factories[token];\n }\n\n private _hasInstance(token: string): boolean {\n return !!this._instances[token];\n }\n\n private _getInstance(token: string, cacheToken: string): T {\n if (!this._hasInstance(cacheToken)) {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories));\n const factory = resolvedToken && this._factories[resolvedToken];\n\n if (!factory) {\n throw new InvalidArgumentError(`'${token}' is not registered.`);\n }\n\n this._instances[cacheToken] = factory();\n }\n\n return this._instances[cacheToken];\n }\n}\n\nexport interface RegistryOptions {\n defaultToken?: string;\n useFallback?: boolean;\n tokenResolver?(token: string, registeredTokens: string[]): string | undefined;\n}\n","import { getDefaultLogger } from '../log';\nimport { getEnvironment } from '../utility';\n\nimport Factory from './factory';\nimport Registry from './registry';\n\nexport default class ResolveIdRegistry {\n private _registry: Registry;\n\n constructor(private _useFallback = false) {\n this._registry = new Registry({\n tokenResolver: this._resolveToken.bind(this),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n register(resolveId: TToken, factory: Factory): void {\n this._registry.register(this._encodeToken(resolveId), factory);\n }\n\n private _encodeToken(resolveId: TToken): string {\n return btoa(JSON.stringify(resolveId));\n }\n\n private _decodeToken(token: string): TToken {\n return JSON.parse(atob(token));\n }\n\n private _resolveToken(token: string, registeredTokens: string[]): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{ token: string; matches: number; default: boolean }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = { token: registeredToken, matches: 0, default: false };\n\n for (const [key, value] of Object.entries(resolverId)) {\n if (key in query && query[key] !== value) {\n result.matches = 0;\n break;\n }\n\n if (key in query && query[key] === value) {\n result.matches++;\n }\n\n if (key === 'default' && value === true) {\n result.default = true;\n }\n }\n\n results.push(result);\n });\n\n const matchedResults = results\n .sort((a, b) => b.matches - a.matches)\n .filter((result) => result.matches > 0);\n\n if (matchedResults.length > 1 && matchedResults[0].matches === matchedResults[1].matches) {\n if (getEnvironment() === 'development') {\n getDefaultLogger().warn(\n 'The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.',\n );\n }\n }\n\n const matched = matchedResults[0];\n\n if (matched && matched.token) {\n return matched.token;\n }\n\n if (this._useFallback) {\n const defaultToken = results.find((result) => result.default)?.token;\n\n if (defaultToken) {\n return defaultToken;\n }\n }\n\n throw new Error('Unable to resolve to a registered token with the provided token.');\n }\n}\n","import CustomError from './custom-error';\nimport setPrototypeOf from './set-prototype-of';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Cart } from '../cart';\n\nimport getLineItemsCount from './getLineItemsCount';\n\nexport default function getShippableItemsCount(cart: Cart): number {\n return getLineItemsCount(cart.lineItems.physicalItems.filter((item) => !item.addedByPromotion));\n}\n","import { reduce } from 'lodash';\n\nimport { LineItem } from '../cart';\n\nexport default function getLineItemsCount(lineItems: LineItem[]): number {\n return reduce(lineItems, (total, item: LineItem) => total + item.quantity, 0);\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import {\n Cart,\n Checkout,\n PaymentIntegrationSelectors,\n PaymentMethod,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\n\nexport interface AmazonPayV2Options {\n environment: EnvironmentType;\n}\n\nexport interface AmazonPayV2SDK {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Pay: AmazonPayV2Client;\n}\n\nexport interface RequestConfig {\n createCheckoutSessionConfig: AmazonPayV2CheckoutSessionConfig;\n estimatedOrderAmount?: AmazonPayV2Price;\n productType?: AmazonPayV2PayOptions;\n}\n\nexport interface AmazonPayV2Button {\n /**\n * Allows you to define custom actions.\n */\n onClick: (callback: () => void | Promise) => void;\n\n /**\n * Initiates the Amazon Pay checkout.\n */\n initCheckout(requestConfig: RequestConfig): void;\n}\n\nexport type AmazonPayV2ButtonParameters = AmazonPayV2ButtonParams | AmazonPayV2NewButtonParams;\n\nexport interface AmazonPayV2Client {\n /**\n * Render the Amazon Pay button to a HTML container element.\n *\n * @param containerId - HTML element id.\n * @param params - Button rendering params.\n */\n renderButton(containerId: string, params: AmazonPayV2ButtonParameters): AmazonPayV2Button;\n\n /**\n * Bind click events to HTML elements, so that when the element is clicked, the buyer can select a different shipping address or payment method.\n *\n * @param buttonId - HTML element id.\n * @param options - Element binding options.\n */\n bindChangeAction(buttonId: string, options: AmazonPayV2ChangeActionOptions): void;\n\n /**\n * Allow buyers to sign out from their Amazon account.\n */\n signout(): void;\n}\n\nexport interface AmazonPayV2HostWindow extends Window {\n amazon?: AmazonPayV2SDK;\n}\n\nexport interface AmazonPayV2ButtonConfig {\n /**\n * Amazon Pay merchant account identifier.\n */\n merchantId: string;\n\n /**\n * Placement of the Amazon Pay button on your website.\n */\n placement: AmazonPayV2Placement;\n\n /**\n * Ledger currency provided during registration for the given merchant identifier.\n */\n ledgerCurrency: AmazonPayV2LedgerCurrency;\n\n /**\n * Product type selected for checkout. Default is 'PayAndShip'.\n */\n productType?: AmazonPayV2PayOptions;\n\n /**\n * Color of the Amazon Pay button.\n */\n buttonColor?: AmazonPayV2ButtonColor;\n\n /**\n * Language used to render the button and text on Amazon Pay hosted pages.\n */\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n\n /**\n * Sets button to Sandbox environment. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix. Default is false.\n */\n sandbox?: boolean;\n\n /**\n * Sets Amazon Pay button design.\n */\n design?: AmazonPayV2ButtonDesign;\n}\n\nexport interface AmazonPayV2ButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Configuration for calling the endpoint to Create Checkout Session.\n */\n createCheckoutSession: AmazonPayV2CheckoutSession;\n}\n\nexport interface AmazonPayV2NewButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Credential provided by Amazon Pay. You must also set the `sandbox`\n * parameter if your `publicKeyId` does not have an environment prefix.\n */\n publicKeyId?: string;\n\n /**\n * It does not have to match the final order amount if the buyer updates\n * their order after starting checkout. Amazon Pay will use this value to\n * assess transaction risk and prevent buyers from selecting payment methods\n * that can't be used to process the order.\n */\n estimatedOrderAmount?: AmazonPayV2Price;\n\n /**\n * Create Checkout Session configuration.\n */\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n}\n\nexport interface AmazonPayV2CheckoutSession {\n /**\n * Endpoint URL to Create Checkout Session.\n */\n url: string;\n\n /**\n * HTTP request method. Default is 'POST'.\n */\n method?: 'GET' | 'POST';\n\n /**\n * Checkout Session ID parameter in the response. Default is 'checkoutSessionId'.\n */\n extractAmazonCheckoutSessionId?: string;\n}\n\nexport interface AmazonPayV2CheckoutSessionConfig {\n /**\n * A payload that Amazon Pay will use to create a Checkout Session object.\n */\n payloadJSON: string;\n\n /**\n * Payload's signature.\n */\n signature: string;\n\n /**\n * Credential provided by Amazon Pay. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix.\n */\n publicKeyId?: string;\n}\n\nexport interface AmazonPayV2Price {\n /**\n * Transaction amount.\n */\n amount: string;\n\n /**\n * Transaction currency code in ISO 4217 format. Example: USD.\n */\n currencyCode: string;\n}\n\nexport type AmazonPayV2ChangeActionType = 'changeAddress' | 'changePayment';\n\nexport interface AmazonPayV2ChangeActionOptions {\n /**\n * Amazon Pay Checkout Session identifier.\n */\n amazonCheckoutSessionId: string;\n\n /**\n * Update requested by the buyer.\n */\n changeAction: AmazonPayV2ChangeActionType;\n}\n\nexport const amazonPayV2Regions: { [key: string]: string } = {\n de: 'eu',\n jp: 'fe',\n uk: 'eu',\n us: 'na',\n};\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum AmazonPayV2CheckoutLanguage {\n en_US = 'en_US',\n en_GB = 'en_GB',\n de_DE = 'de_DE',\n fr_FR = 'fr_FR',\n it_IT = 'it_IT',\n es_ES = 'es_ES',\n ja_JP = 'ja_JP',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/* eslint-disable @typescript-eslint/no-shadow */\nexport enum AmazonPayV2Placement {\n /** Initial or main page. */\n Home = 'Home',\n\n /** Product details page. */\n Product = 'Product',\n\n /** Cart review page before buyer starts checkout. */\n Cart = 'Cart',\n\n /** Any page after buyer starts checkout. */\n Checkout = 'Checkout',\n\n /** Any page that doesn't fit the previous descriptions. */\n Other = 'Other',\n}\n/* eslint-enable @typescript-eslint/no-shadow */\n\nexport enum AmazonPayV2LedgerCurrency {\n USD = 'USD',\n EUR = 'EUR',\n GBP = 'GBP',\n JPY = 'JPY',\n}\n\nexport enum AmazonPayV2PayOptions {\n /** Select this product type if you need the buyer's shipping details. */\n PayAndShip = 'PayAndShip',\n\n /** Select this product type if you do not need the buyer's shipping details. */\n PayOnly = 'PayOnly',\n}\n\nexport enum AmazonPayV2ButtonColor {\n Gold = 'Gold',\n LightGray = 'LightGray',\n DarkGray = 'DarkGray',\n}\n\nexport enum AmazonPayV2ButtonDesign {\n C0001 = 'C0001',\n}\n\n// TODO: after migration AmazonPay strategies to integration package\n// should be removed\n// and replaced usage with \nexport interface InternalCheckoutSelectors {\n cart: {\n getCart: () => Cart | undefined;\n };\n checkout: {\n getCheckout: () => Checkout | undefined;\n };\n config: {\n getStoreConfigOrThrow: () => StoreConfig;\n };\n paymentMethods: {\n getPaymentMethodOrThrow: (methodId: string) => PaymentMethod;\n };\n}\n\nexport interface AmazonPayV2InitializeOptions {\n buttonColor?: AmazonPayV2ButtonColor;\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n checkoutSessionMethod?: 'GET' | 'POST';\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n extractAmazonCheckoutSessionId?: string;\n ledgerCurrency?: AmazonPayV2LedgerCurrency;\n publicKeyId?: string;\n region?: string;\n isButtonMicroTextDisabled?: boolean;\n paymentToken?: string;\n}\n\nexport interface AmazonPayV2ButtonRenderingOptions {\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors;\n containerId: string;\n decoupleCheckoutInitiation?: boolean;\n methodId: string;\n buttonColor?: AmazonPayV2ButtonColor;\n options?: AmazonPayV2ButtonParameters;\n placement: AmazonPayV2Placement;\n isButtonMicroTextDisabled?: boolean;\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport interface AmazonPayAdditionalActionErrorBody {\n status: string;\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n","import {\n CheckoutSettings,\n getShippableItemsCount,\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationSelectors,\n PaymentMethod,\n StoreProfile,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AmazonPayV2Button,\n AmazonPayV2ButtonColor,\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonDesign,\n AmazonPayV2ButtonParameters,\n AmazonPayV2ButtonRenderingOptions,\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2NewButtonParams,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n AmazonPayV2Price,\n AmazonPayV2SDK,\n InternalCheckoutSelectors,\n RequestConfig,\n} from './amazon-pay-v2';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\nimport { isInternalCheckoutSelectors } from './isInternalCheckoutSelectors';\n\nexport default class AmazonPayV2PaymentProcessor {\n private amazonPayV2SDK?: AmazonPayV2SDK;\n private buttonParentContainer?: HTMLDivElement;\n private amazonPayV2Button?: AmazonPayV2Button;\n private isBuyNowFlow?: boolean;\n\n constructor(private amazonPayV2ScriptLoader: AmazonPayV2ScriptLoader) {}\n\n async initialize(paymentMethod: PaymentMethod): Promise {\n this.amazonPayV2SDK = await this.amazonPayV2ScriptLoader.load(paymentMethod);\n this.buttonParentContainer =\n this.buttonParentContainer || this.createAmazonPayButtonParentContainer();\n }\n\n deinitialize(): Promise {\n this.amazonPayV2Button = undefined;\n this.buttonParentContainer?.remove();\n this.buttonParentContainer = undefined;\n this.amazonPayV2SDK = undefined;\n\n return Promise.resolve();\n }\n\n bindButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n ): void {\n this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${buttonId}`, {\n amazonCheckoutSessionId: sessionId,\n changeAction,\n });\n }\n\n createButton(containerId: string, options: AmazonPayV2ButtonParameters): void {\n this.amazonPayV2Button = this.getAmazonPayV2SDK().Pay.renderButton(\n `#${containerId}`,\n options,\n );\n }\n\n prepareCheckout(createCheckoutSessionConfig: Required) {\n const requestConfig = this.prepareRequestConfig(createCheckoutSessionConfig);\n\n this.getAmazonPayV2Button().onClick(() => {\n this.getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n prepareCheckoutWithCreationRequestConfig(\n createCheckoutConfig: () => Promise<\n | {\n createCheckoutSessionConfig: Required;\n estimatedOrderAmount: AmazonPayV2Price;\n productType: AmazonPayV2PayOptions;\n }\n | undefined\n >,\n ) {\n this.getAmazonPayV2Button().onClick(async () => {\n const config = await createCheckoutConfig();\n\n if (config) {\n const requestConfig = this.prepareRequestConfig(\n config.createCheckoutSessionConfig,\n config.estimatedOrderAmount,\n config.productType,\n );\n\n this.getAmazonPayV2Button().initCheckout(requestConfig);\n }\n });\n }\n\n async signout(): Promise {\n if (this.amazonPayV2SDK) {\n this.amazonPayV2SDK.Pay.signout();\n }\n\n return Promise.resolve();\n }\n\n renderAmazonPayButton({\n buttonColor,\n checkoutState,\n containerId,\n decoupleCheckoutInitiation = false,\n methodId,\n options,\n placement,\n isButtonMicroTextDisabled = false,\n }: AmazonPayV2ButtonRenderingOptions): HTMLDivElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\n }\n\n const { id: parentContainerId } = container.appendChild(this.getButtonParentContainer());\n\n if (options && isButtonMicroTextDisabled) {\n options.design = AmazonPayV2ButtonDesign.C0001;\n }\n\n const amazonPayV2ButtonOptions =\n options ??\n this.getAmazonPayV2ButtonOptions(\n checkoutState,\n methodId,\n placement,\n decoupleCheckoutInitiation,\n buttonColor,\n );\n\n this.createButton(parentContainerId, amazonPayV2ButtonOptions);\n\n return this.getButtonParentContainer();\n }\n\n updateBuyNowFlowFlag(isBuyNowFlow?: boolean) {\n this.isBuyNowFlow = Boolean(isBuyNowFlow);\n }\n\n /**\n * @internal\n */\n isPh4Enabled(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n const isPh4Enabled = !!features['PROJECT-3483.amazon_pay_ph4'];\n const isPh4UsOnly = !!features['INT-6885.amazon_pay_ph4_us_only'];\n\n if (isPh4Enabled && isPh4UsOnly) {\n return storeCountryCode === 'US';\n }\n\n return isPh4Enabled;\n }\n\n private prepareRequestConfig(\n createCheckoutSessionConfig: Required,\n estimatedOrderAmount?: AmazonPayV2Price,\n productType?: AmazonPayV2PayOptions,\n ): RequestConfig {\n const { publicKeyId, ...signedPayload } = createCheckoutSessionConfig;\n\n return {\n createCheckoutSessionConfig: this.isEnvironmentSpecific(publicKeyId)\n ? signedPayload\n : createCheckoutSessionConfig,\n ...(estimatedOrderAmount && { estimatedOrderAmount }),\n ...(productType && { productType }),\n };\n }\n\n private createAmazonPayButtonParentContainer(): HTMLDivElement {\n const uid = Math.random().toString(16).substr(-4);\n const parentContainer = document.createElement('div');\n\n parentContainer.id = `amazonpay_button_parent_container_${uid}`;\n\n return parentContainer;\n }\n\n private getAmazonPayV2ButtonOptions(\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors,\n methodId: string,\n placement: AmazonPayV2Placement,\n decoupleCheckoutInitiation = false,\n buttonColor = AmazonPayV2ButtonColor.Gold,\n ): AmazonPayV2ButtonParameters {\n const { getCart, getCheckout, getStoreConfigOrThrow, getPaymentMethodOrThrow } =\n this.getCheckoutState(checkoutState);\n const {\n config: { merchantId, testMode },\n initializationData,\n } = getPaymentMethodOrThrow(methodId);\n\n if (!initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n checkoutLanguage,\n checkoutSessionMethod,\n createCheckoutSessionConfig,\n extractAmazonCheckoutSessionId,\n ledgerCurrency,\n publicKeyId = '',\n isButtonMicroTextDisabled,\n } = initializationData;\n\n if (!merchantId || !ledgerCurrency || !createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const buttonBaseConfig: AmazonPayV2ButtonConfig = {\n merchantId,\n ledgerCurrency,\n checkoutLanguage,\n placement,\n buttonColor,\n ...(isButtonMicroTextDisabled ? { design: AmazonPayV2ButtonDesign.C0001 } : {}),\n };\n\n if (this.isBuyNowFlow) {\n return {\n ...buttonBaseConfig,\n sandbox: !!testMode,\n };\n }\n\n const cart = getCart();\n\n buttonBaseConfig.productType =\n cart && getShippableItemsCount(cart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip;\n\n const {\n checkoutSettings: { features },\n storeProfile: { shopPath, storeCountryCode },\n } = getStoreConfigOrThrow();\n\n if (this.isPh4Enabled(features, storeCountryCode)) {\n const amount = getCheckout()?.outstandingBalance.toString();\n const currencyCode = cart?.currency.code;\n const buttonOptions: AmazonPayV2NewButtonParams = { ...buttonBaseConfig };\n let tmpConfig: AmazonPayV2CheckoutSessionConfig;\n\n if (this.isEnvironmentSpecific(publicKeyId)) {\n buttonOptions.publicKeyId = publicKeyId;\n tmpConfig = createCheckoutSessionConfig;\n } else {\n buttonOptions.sandbox = !!testMode;\n tmpConfig = { ...createCheckoutSessionConfig, publicKeyId };\n }\n\n if (!decoupleCheckoutInitiation) {\n buttonOptions.createCheckoutSessionConfig = tmpConfig;\n }\n\n if (amount && currencyCode) {\n buttonOptions.estimatedOrderAmount = { amount, currencyCode };\n }\n\n return buttonOptions;\n }\n\n const createCheckoutSession = {\n method: checkoutSessionMethod,\n url: features['INT-5826.amazon_relative_url']\n ? `/remote-checkout/${methodId}/payment-session`\n : `${shopPath}/remote-checkout/${methodId}/payment-session`,\n extractAmazonCheckoutSessionId,\n };\n\n return {\n ...buttonBaseConfig,\n createCheckoutSession,\n sandbox: !!testMode,\n };\n }\n\n private isEnvironmentSpecific(publicKeyId: string): boolean {\n return /^(SANDBOX|LIVE)/.test(publicKeyId);\n }\n\n private getAmazonPayV2SDK(): AmazonPayV2SDK {\n return this.getOrThrow(this.amazonPayV2SDK);\n }\n\n private getButtonParentContainer(): HTMLDivElement {\n return this.getOrThrow(this.buttonParentContainer);\n }\n\n private getAmazonPayV2Button(): AmazonPayV2Button {\n return this.getOrThrow(this.amazonPayV2Button);\n }\n\n private getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n // INFO: need this mapping while we have strategies in core and in integration package at the same time\n private getCheckoutState(\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors,\n ): Pick<\n PaymentIntegrationSelectors,\n 'getCart' | 'getCheckout' | 'getStoreConfigOrThrow' | 'getPaymentMethodOrThrow'\n > {\n if (isInternalCheckoutSelectors(checkoutState)) {\n return {\n getCart: checkoutState.cart.getCart,\n getCheckout: checkoutState.checkout.getCheckout,\n getStoreConfigOrThrow: checkoutState.config.getStoreConfigOrThrow,\n getPaymentMethodOrThrow: (methodId: string) =>\n checkoutState.paymentMethods.getPaymentMethodOrThrow(methodId),\n };\n }\n\n return checkoutState;\n }\n}\n","import { InternalCheckoutSelectors } from './amazon-pay-v2';\n\nexport function isInternalCheckoutSelectors(\n checkoutSelectors: unknown,\n): checkoutSelectors is InternalCheckoutSelectors {\n return (\n typeof checkoutSelectors === 'object' &&\n checkoutSelectors !== null &&\n 'cart' in checkoutSelectors &&\n 'checkout' in checkoutSelectors &&\n 'config' in checkoutSelectors &&\n 'paymentMethods' in checkoutSelectors\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AmazonPayV2HostWindow,\n AmazonPayV2InitializeOptions,\n amazonPayV2Regions,\n AmazonPayV2SDK,\n} from './amazon-pay-v2';\n\nexport default class AmazonPayV2ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private windowWithAmazonPay: AmazonPayV2HostWindow = window,\n ) {}\n\n async load(method: PaymentMethod): Promise {\n const { initializationData } = method;\n const region = initializationData?.region || 'us';\n\n const amazonPayV2Region = amazonPayV2Regions[region];\n\n await this.scriptLoader.loadScript(\n `https://static-${amazonPayV2Region}.payments-amazon.com/checkout.js`,\n );\n\n if (!this.windowWithAmazonPay.amazon) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.windowWithAmazonPay.amazon;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default function createAmazonPayV2PaymentProcessor(): AmazonPayV2PaymentProcessor {\n return new AmazonPayV2PaymentProcessor(new AmazonPayV2ScriptLoader(getScriptLoader()));\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function toResolvableModule(\n module: TModule,\n resolveIds: TIdentifier[],\n): ResolvableModule {\n return Object.assign(module, { resolveIds });\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import {\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithAmazonPayV2CustomerInitializeOptions } from './amazon-pay-v2-customer-initialize-options';\n\nexport default class AmazonPayV2CustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithAmazonPayV2CustomerInitializeOptions,\n ): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId || !amazonpay?.container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this.paymentIntegrationService.getState(),\n containerId: amazonpay.container,\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n }\n\n async deinitialize(): Promise {\n await this.amazonPayV2PaymentProcessor.deinitialize();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Amazon, the shopper must click on \"Amazon Pay\" button.',\n );\n }\n\n async signOut(options?: RequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n\n if (!payment) {\n return;\n }\n\n await this.amazonPayV2PaymentProcessor.signout();\n await this.paymentIntegrationService.remoteCheckoutSignOut(payment.providerId, options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n}\n","import { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2CustomerStrategy from './amazon-pay-v2-customer-strategy';\n\nconst createAmazonPayV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AmazonPayV2CustomerStrategy(\n paymentIntegrationService,\n createAmazonPayV2PaymentProcessor(),\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2CustomerStrategy, [{ id: 'amazonpay' }]);\n","import { StandardError } from './index';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","export * from './braintree';\nexport * from './paypal';\nexport * from './visacheckout';\n\n/**\n *\n * Braintree Module\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string; // Info: authorization uses clientToken as a value\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\n/**\n *\n * Braintree Window\n *\n */\nexport interface BraintreeWindow extends Window {\n client?: BraintreeClientCreator;\n braintreeFastlane?: BraintreeFastlane;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeClientRequestPayload): Promise;\n}\n\nexport interface BraintreeClientRequestPayload {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeClientRequestResponse {\n creditCards: BraintreeHostedFieldsTokenizePayload[];\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean; // Info: this param is needed for fraud detection (should always be 'true')\n paypal?: boolean; // TODO: based on braintree documentation, this param is deprecated, so we dont need it anymore\n riskCorrelationId?: string; // Info: the option is needed for PayPal Analytics\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n// TODO: remove this interface when BraintreeIntegrationService will be removed\nexport interface BraintreeDataCollectors {\n default?: BraintreeDataCollector;\n paypal?: BraintreeDataCollector;\n}\n\n/**\n *\n * Braintree Google Payment\n *\n */\ntype BraintreeGooglePaymentAddressFormat = 'FULL' | 'MIN';\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\nexport interface BraintreeGooglePaymentDataRequestOptions {\n merchantInfo: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n transactionInfo: {\n currencyCode: string;\n totalPriceStatus: TotalPriceStatusType;\n totalPrice: string;\n };\n cardRequirements: {\n billingAddressRequired: boolean;\n billingAddressFormat: BraintreeGooglePaymentAddressFormat;\n };\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n shippingAddressRequired?: boolean;\n}\n\nexport interface BraintreeGooglePaymentDataRequest {\n allowedPaymentMethods: string[];\n apiVersion: number;\n cardRequirements: {\n allowedCardNetworks: string[];\n billingAddressFormat: string;\n billingAddressRequired: boolean;\n };\n environment: string;\n i: {\n googleTransactionId: string;\n startTimeMs: number;\n };\n merchantInfo: {\n merchantId: string;\n merchantName: string;\n authJwt?: string;\n };\n paymentMethodTokenizationParameters: {\n parameters: {\n 'braintree:apiVersion': string;\n 'braintree:authorizationFingerprint': string;\n 'braintree:merchantId': string;\n 'braintree:metadata': string;\n 'braintree:sdkVersion': string;\n gateway: string;\n };\n tokenizationType: string;\n };\n shippingAddressRequired: boolean;\n phoneNumberRequired: boolean;\n transactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport type BraintreeGooglePaymentCreator = BraintreeModuleCreator;\n\nexport interface BraintreeGooglePayment extends BraintreeModule {\n createPaymentDataRequest(\n options?: BraintreeGooglePaymentDataRequestOptions,\n ): BraintreeGooglePaymentDataRequest;\n}\n\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n bin: string;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n addFrame?(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n removeFrame?(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\nexport interface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree US Bank Account (ACH)\n *\n */\nexport type BraintreeUsBankAccountCreator = BraintreeModuleCreator;\n\nexport interface BraintreeUsBankAccount {\n tokenize(\n options: BraintreeUsBankAccountTokenizationOptions,\n ): Promise;\n}\n\nexport interface BraintreeUsBankAccountTokenizationOptions {\n bankDetails: BraintreeUsBankAccountDetails;\n mandateText: string;\n}\n\nexport interface BraintreeUsBankAccountTokenizationResponse {\n nonce: string;\n details: BraintreeTokenizationDetails;\n}\n\nexport interface BraintreeUsBankAccountDetails {\n accountNumber: string;\n routingNumber: string;\n ownershipType: string;\n accountType: string;\n firstName?: string;\n lastName?: string;\n businessName?: string;\n billingAddress: {\n streetAddress: string;\n extendedAddress: string;\n locality: string;\n region: string;\n postalCode: string;\n };\n}\n\n// TODO: move this interface in separate types group if it will be used in another (not ACH) strategies\n// This seems to be an interface which will be used in different places\nexport interface BraintreeTokenizationDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\n/**\n *\n * Braintree Fastlane\n *\n */\nexport type BraintreeFastlaneCreator = BraintreeModuleCreator<\n BraintreeFastlane,\n BraintreeFastlaneConfig\n>;\n\nexport interface BraintreeFastlaneConfig {\n authorization: string;\n client: BraintreeClient;\n deviceData?: string;\n styles?: BraintreeFastlaneStylesOption;\n}\n\nexport interface BraintreeFastlane {\n identity: BraintreeFastlaneIdentity;\n profile: BraintreeFastlaneProfile;\n FastlaneCardComponent: (\n options: BraintreeFastlaneCardComponentOptions,\n ) => Promise;\n events: BraintreeFastlaneEvents;\n}\n\nexport interface BraintreeFastlaneProfile {\n showCardSelector(): Promise;\n showShippingAddressSelector(): Promise;\n}\n\nexport interface BraintreeFastlaneShippingAddressSelectorResponse {\n selectionChanged: boolean;\n selectedAddress: BraintreeFastlaneShippingAddress;\n}\n\nexport interface BraintreeFastlaneShippingAddress {\n name: BraintreeFastlaneProfileName;\n phoneNumber: string;\n id?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress: string;\n extendedAddress?: string;\n locality: string;\n region: string;\n postalCode: string;\n countryCodeNumeric?: number;\n countryCodeAlpha2: string;\n countryCodeAlpha3?: string;\n}\n\nexport interface BraintreeFastlaneProfileName {\n fullName: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface BraintreeFastlaneCardSelectorResponse {\n selectionChanged: boolean;\n selectedCard: BraintreeFastlaneVaultedInstrument;\n}\n\nexport interface BraintreeFastlaneWindow extends Window {\n braintreeFastlane: BraintreeFastlane;\n}\n\nexport interface BraintreeFastlaneIdentity {\n lookupCustomerByEmail(email: string): Promise;\n triggerAuthenticationFlow(\n customerId: string,\n options?: BraintreeFastlaneAuthenticationOptions,\n ): Promise;\n}\n\nexport interface BraintreeFastlaneLookupCustomerByEmailResult {\n customerContextId?: string;\n}\n\nexport interface BraintreeFastlaneAuthenticationOptions {\n styles?: BraintreeFastlaneStylesOption;\n}\n\nexport interface BraintreeFastlaneStylesOption {\n root?: {\n backgroundColorPrimary?: string;\n errorColor?: string;\n fontFamily?: string;\n fontSizeBase?: string;\n padding?: string;\n primaryColor?: string;\n };\n input?: {\n borderRadius?: string;\n borderColor?: string;\n focusBorderColor?: string;\n backgroundColor?: string;\n borderWidth?: string;\n textColorBase?: string;\n };\n toggle?: {\n colorPrimary?: string;\n colorSecondary?: string;\n };\n text?: {\n body?: {\n color?: string;\n fontSize?: string;\n };\n caption?: {\n color?: string;\n fontSize?: string;\n };\n };\n branding?: string; // 'light' | 'dark'\n}\n\nexport enum BraintreeFastlaneAuthenticationState {\n SUCCEEDED = 'succeeded',\n FAILED = 'failed',\n CANCELED = 'cancelled',\n UNRECOGNIZED = 'unrecognized',\n}\n\nexport interface BraintreeFastlaneAuthenticationCustomerResult {\n authenticationState: BraintreeFastlaneAuthenticationState;\n profileData: BraintreeFastlaneProfileData;\n}\n\nexport interface BraintreeFastlaneProfileData {\n fastlaneCustomerAuthAssertionToken: string;\n fastlaneCustomerId: string;\n shippingAddress: BraintreeFastlaneAddress;\n card: BraintreeFastlaneVaultedInstrument;\n name: BraintreeFastlaneName;\n}\n\nexport interface BraintreeFastlaneName {\n firstName: string;\n lastName: string;\n}\n\nexport interface BraintreeFastlaneAddress {\n id?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress: string;\n extendedAddress?: string;\n locality: string;\n region: string;\n postalCode: string;\n countryCodeNumeric?: number;\n countryCodeAlpha2: string;\n countryCodeAlpha3?: string;\n phoneNumber?: string;\n}\n\nexport interface BraintreeFastlaneCardPaymentSource {\n brand: string;\n expiry: string;\n lastDigits: string;\n name?: string;\n billingAddress: BraintreeFastlaneAddress;\n}\n\nexport interface BraintreeFastlanePaymentSource {\n card: BraintreeFastlaneCardPaymentSource;\n}\n\nexport interface BraintreeFastlaneVaultedInstrument {\n id: string; // This is the nonce / token\n paymentSource: BraintreeFastlanePaymentSource;\n}\n\nexport interface BraintreeFastlaneCardComponentOptions {\n styles: BraintreeFastlaneStylesOption;\n fields: BraintreeFastlaneCardComponentFields;\n}\n\nexport interface BraintreeFastlaneCardComponentFields {\n cardholderName?: {\n enabled?: boolean;\n prefill?: string;\n };\n phoneNumber?: {\n placeholder?: string;\n prefill?: string;\n };\n}\n\nexport interface FastlaneStylesSettings {\n fastlaneRootSettingsBackgroundColor?: string;\n fastlaneRootSettingsErrorColor?: string;\n fastlaneRootSettingsFontFamily?: string;\n fastlaneRootSettingsPadding?: string;\n fastlaneRootSettingsPrimaryColor?: string;\n fastlaneRootSettingsFontSize?: string;\n fastlaneInputSettingsBackgroundColor?: string;\n fastlaneInputSettingsBorderRadius?: string;\n fastlaneInputSettingsBorderWidth?: string;\n fastlaneInputSettingsBorderColor?: string;\n fastlaneInputSettingsFocusBorderBase?: string;\n fastlaneInputSettingsTextColorBase?: string;\n fastlaneToggleSettingsColorPrimary?: string;\n fastlaneToggleSettingsColorSecondary?: string;\n fastlaneTextBodySettingsColor?: string;\n fastlaneTextBodySettingsFontSize?: string;\n fastlaneTextCaptionSettingsFontSize?: string;\n fastlaneTextCaptionSettingsColor?: string;\n fastlaneBrandingSettings?: string;\n}\n\nexport interface BraintreeFastlaneTokenizeOptions {\n name?: {\n fullName: string;\n };\n billingAddress?: BraintreeFastlaneAddress;\n shippingAddress?: BraintreeFastlaneAddress;\n}\n\nexport interface BraintreeFastlaneEvents {\n apmSelected: (options: BraintreeFastlaneApmSelectedEventOptions) => void;\n emailSubmitted: (options: BraintreeFastlaneEmailEnteredEventOptions) => void;\n orderPlaced: (options: BraintreeFastlaneOrderPlacedEventOptions) => void;\n}\n\nexport interface BraintreeFastlaneEventCommonOptions {\n context_type: 'cs_id';\n context_id: string; // checkout session id\n page_type: 'checkout_page';\n page_name: string; // title of the checkout initiation page\n partner_name: 'bigc';\n user_type: 'store_member' | 'store_guest'; // type of the user on the merchant site\n store_id: string;\n merchant_name: string;\n experiment: string; // stringify JSON object \"[{ treatment_group: 'test' | 'control' }]\"\n}\n\nexport interface BraintreeFastlaneApmSelectedEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page\n apm_selected: string; // alternate payment method selected / methodId\n apm_location: 'pre-email section' | 'payment section'; // placement of APM, whether it be above the email entry or in the radio buttons\n}\n\nexport interface BraintreeFastlaneEmailEnteredEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n user_email_saved: boolean; // shows whether checkout was loaded with or without a saved email\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page 'applepay,googlepay,paypal'\n}\n\nexport interface BraintreeFastlaneOrderPlacedEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n selected_payment_method: string;\n currency_code: string;\n}\n\nexport interface BraintreeFastlaneCardComponent {\n (options: BraintreeFastlaneCardComponentOptions): BraintreeFastlaneCardComponent;\n getPaymentToken(\n options: BraintreeFastlaneTokenizeOptions,\n ): Promise;\n render(element: string): void;\n}\n\n/**\n *\n * Braintree Payload Verification\n *\n */\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\n/**\n *\n * Braintree Errors\n *\n */\nexport enum BraintreeErrorType {\n Customer = 'CUSTOMER',\n Merchant = 'MERCHANT',\n Network = 'NETWORK',\n Internal = 'INTERNAL',\n Unknown = 'UNKNOWN',\n}\n\nexport enum BraintreeErrorCode {\n KountNotEnabled = 'DATA_COLLECTOR_KOUNT_NOT_ENABLED',\n}\n\nexport interface BraintreeError extends Error {\n type: BraintreeErrorType;\n code: string | BraintreeErrorCode.KountNotEnabled;\n details?: unknown;\n}\n\n/**\n *\n * Braintree non-instant payment methods\n *\n */\n\nexport enum NonInstantLocalPaymentMethods {\n TRUSTLY = 'trustly',\n}\n\nexport interface BraintreeLocalPaymentMethodRedirectAction {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport interface BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\n}\n","import { BraintreeError } from '../types';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return Boolean(\n typeof error === 'object' &&\n error !== null &&\n ('type' in error || 'message' in error || 'code' in error),\n );\n}\n","import {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig,\n BraintreeError,\n BraintreeErrorCode,\n BraintreeGooglePayment,\n BraintreeLocalPayment,\n BraintreeModule,\n BraintreeThreeDSecure,\n BraintreeUsBankAccount,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport { VisaCheckoutSDK } from './visacheckout';\n\nexport default class BraintreeSdk {\n private braintreeVenmo?: BraintreeVenmoCheckout;\n private braintreeLocalPayment?: BraintreeLocalPayment;\n private client?: BraintreeClient;\n private clientToken?: string;\n private dataCollector?: BraintreeDataCollector;\n private googlePayment?: BraintreeGooglePayment;\n private threeDS?: BraintreeThreeDSecure;\n private visaCheckout?: Promise;\n private visaCheckoutSDK?: VisaCheckoutSDK;\n private usBankAccount?: BraintreeUsBankAccount;\n\n constructor(private braintreeScriptLoader: BraintreeScriptLoader) {}\n\n initialize(clientToken: string): void {\n this.setClientToken(clientToken);\n }\n\n async deinitialize(): Promise {\n await this.teardownModule(this.dataCollector);\n\n this.dataCollector = undefined;\n }\n\n /**\n *\n * Braintree Client\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_client.html\n *\n */\n async getClient(): Promise {\n if (!this.client) {\n const clientToken = this.getClientTokenOrThrow();\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = await clientCreator.create({ authorization: clientToken });\n }\n\n return this.client;\n }\n\n /**\n *\n * Braintree Data collector\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_data-collector.html\n *\n */\n async getDataCollectorOrThrow(\n options?: Partial,\n ): Promise {\n const emptyDataCollector = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n\n if (!this.dataCollector) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n const dataCollectorConfig: BraintreeDataCollectorCreatorConfig = {\n client,\n kount: true,\n ...options,\n };\n\n this.dataCollector = await dataCollector.create(dataCollectorConfig);\n } catch (error) {\n if (isBraintreeError(error) && error.code === BraintreeErrorCode.KountNotEnabled) {\n return emptyDataCollector;\n }\n\n throw error;\n }\n }\n\n return this.dataCollector;\n }\n\n /**\n *\n * Braintree Google Payment\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_google-payment.html\n *\n */\n async getBraintreeGooglePayment(): Promise {\n if (!this.googlePayment) {\n const [client, braintreeGooglePayment] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadGooglePayment(),\n ]);\n\n this.googlePayment = await braintreeGooglePayment.create({ client });\n }\n\n return this.googlePayment;\n }\n\n /**\n *\n * Braintree 3DS\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_three-d-secure.html\n *\n */\n async getBraintreeThreeDS(): Promise {\n if (!this.threeDS) {\n const [client, threeDSecure] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]);\n\n this.threeDS = await threeDSecure.create({ client, version: 2 });\n }\n\n return this.threeDS;\n }\n\n /**\n *\n * Braintree Local Payment Methods\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_local-payment.html\n *\n */\n async getBraintreeLocalPayment(\n merchantAccountId: string,\n ): Promise {\n if (!this.braintreeLocalPayment) {\n const [client, localPaymentCreator] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadLocalPayment(),\n ]);\n\n this.braintreeLocalPayment = await new Promise(\n (\n resolve: (braintreeLocalPayment: BraintreeLocalPayment) => void,\n reject: (error: BraintreeError) => void,\n ) => {\n void localPaymentCreator.create(\n { client, merchantAccountId },\n (\n error: BraintreeError | undefined,\n braintreeLocalPayment: BraintreeLocalPayment,\n ) => {\n if (error) {\n reject(error);\n }\n\n resolve(braintreeLocalPayment);\n },\n );\n },\n );\n }\n\n return this.braintreeLocalPayment;\n }\n\n /**\n *\n * Braintree UsBankAccount\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_us-bank-account.html\n *\n */\n async getUsBankAccount() {\n if (!this.usBankAccount) {\n const client = await this.getClient();\n const usBankAccount = await this.braintreeScriptLoader.loadUsBankAccount();\n\n this.usBankAccount = await usBankAccount.create({ client });\n }\n\n return this.usBankAccount;\n }\n\n /**\n *\n * Braintree Visa Checkout\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_visa-checkout.html\n *\n */\n getBraintreeVisaCheckout() {\n if (!this.visaCheckout) {\n this.visaCheckout = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this.visaCheckout;\n }\n\n /**\n *\n * Braintree Visa Checkout SDK\n * visa checkout doc: https://developer.visa.com/capabilities/visa_checkout/docs-how-to\n *\n */\n async getVisaCheckoutSdk(testMode?: boolean) {\n if (!this.visaCheckoutSDK) {\n this.visaCheckoutSDK = await this.braintreeScriptLoader.loadVisaCheckoutSdk(testMode);\n }\n\n return this.visaCheckoutSDK;\n }\n\n /**\n *\n * Braintree Venmo Checkout\n * braintree venmo checkout doc: https://braintree.github.io/braintree-web/current/module-braintree-web_venmo.html\n *\n */\n async getVenmoCheckoutOrThrow() {\n if (!this.braintreeVenmo) {\n const client = await this.getClient();\n const venmoCheckout = await this.braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const braintreeVenmoCheckout = await venmoCheckout.create(venmoCheckoutConfig);\n\n if (braintreeVenmoCheckout.isBrowserSupported()) {\n this.braintreeVenmo = braintreeVenmoCheckout;\n } else {\n throw new UnsupportedBrowserError();\n }\n }\n\n return this.braintreeVenmo;\n }\n\n /**\n *\n * Private methods\n *\n */\n private setClientToken(clientToken: string): void {\n this.clientToken = clientToken;\n }\n\n private getClientTokenOrThrow(): string {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.clientToken;\n }\n\n private teardownModule(module?: BraintreeModule): Promise {\n return module ? module.teardown() : Promise.resolve();\n }\n}\n","import { Omit } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PaypalAuthorizeData,\n PaypalButtonOptions,\n PaypalButtonRender,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal';\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeError,\n BraintreeFastlaneCreator,\n BraintreeGooglePaymentCreator,\n BraintreeHostedFieldsTokenizePayload,\n BraintreeModule,\n BraintreeModuleCreator,\n BraintreeModuleCreatorConfig,\n BraintreeThreeDSecureCreator,\n BraintreeTokenizationDetails,\n BraintreeUsBankAccountCreator,\n BraintreeWindow,\n FastlaneStylesSettings,\n VisaCheckoutSDK,\n} from './types';\nimport {\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\n/**\n *\n * Constants\n *\n */\nexport enum BraintreeEnv {\n Sandbox = 'sandbox',\n Production = 'production',\n}\n\n/**\n *\n * Common\n *\n */\nexport enum BraintreeModuleName {\n Client = 'client',\n DataCollector = 'dataCollector',\n Fastlane = 'fastlane',\n GooglePayment = 'googlePayment',\n HostedFields = 'hostedFields',\n LocalPayment = 'localPayment',\n Paypal = 'paypal',\n PaypalCheckout = 'paypalCheckout',\n ThreeDSecure = 'threeDSecure',\n UsBankAccount = 'usBankAccount',\n Venmo = 'venmo',\n VisaCheckout = 'visaCheckout',\n}\n\nexport type BraintreeModuleCreators =\n | BraintreeClientCreator\n | BraintreeFastlaneCreator\n | BraintreeDataCollectorCreator\n | BraintreeGooglePaymentCreator\n | BraintreeHostedFieldsCreator\n | BraintreePaypalCreator\n | BraintreePaypalCheckoutCreator\n | BraintreeThreeDSecureCreator\n | BraintreeVenmoCheckoutCreator\n | BraintreeVisaCheckoutCreator\n | BraintreeUsBankAccountCreator\n | BraintreeLocalPaymentCreator;\n\n// TODO: rename to BraintreeSdkModules\nexport interface BraintreeSDK {\n [BraintreeModuleName.Client]?: BraintreeClientCreator;\n [BraintreeModuleName.Fastlane]?: BraintreeFastlaneCreator;\n [BraintreeModuleName.DataCollector]?: BraintreeDataCollectorCreator;\n [BraintreeModuleName.GooglePayment]?: BraintreeGooglePaymentCreator;\n [BraintreeModuleName.HostedFields]?: BraintreeHostedFieldsCreator;\n [BraintreeModuleName.Paypal]?: BraintreePaypalCreator;\n [BraintreeModuleName.PaypalCheckout]?: BraintreePaypalCheckoutCreator;\n [BraintreeModuleName.ThreeDSecure]?: BraintreeThreeDSecureCreator;\n [BraintreeModuleName.Venmo]?: BraintreeVenmoCheckoutCreator;\n [BraintreeModuleName.VisaCheckout]?: BraintreeVisaCheckoutCreator;\n [BraintreeModuleName.UsBankAccount]?: BraintreeUsBankAccountCreator;\n [BraintreeModuleName.LocalPayment]?: BraintreeLocalPaymentCreator;\n}\n\nexport type BraintreeLocalPaymentCreator = BraintreeModuleCreator<\n BraintreeLocalPayment,\n BraintreeLocalPaymentCreateConfig,\n BraintreeError | undefined\n>;\n\nexport interface BraintreeLocalPaymentCreateConfig extends BraintreeModuleCreatorConfig {\n merchantAccountId: string;\n}\n\nexport interface BraintreeInitializationData {\n clientToken: string;\n intent?: 'authorize' | 'order' | 'sale';\n isCreditEnabled?: boolean;\n isAcceleratedCheckoutEnabled?: boolean;\n isFastlaneStylingEnabled?: boolean;\n isFastlaneEnabled?: boolean;\n isFastlaneShippingOptionAutoSelectEnabled?: boolean;\n fastlaneStyles?: FastlaneStylesSettings;\n isBraintreeAnalyticsV2Enabled?: boolean;\n shouldRunAcceleratedCheckout?: boolean; // TODO: only for BT AXO A/B testing purposes, hence should be removed after testing\n paymentButtonStyles?: Record;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeTokenizationDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport type BraintreeFormErrorData = Omit;\n\nexport type BraintreeFormErrorDataKeys =\n | 'number'\n | 'expirationDate'\n | 'expirationMonth'\n | 'expirationYear'\n | 'cvv'\n | 'postalCode';\n\nexport type BraintreeFormErrorsData = Partial<\n Record\n>;\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n getState(): BraintreeHostedFieldsState;\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n cardholderName?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\nexport interface BraintreeFormFieldState {\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface TokenizationPayload {\n nonce: string;\n bin: string;\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\n// export interface BraintreeThreeDSecureOptions {\n// /**\n// * A callback that gets called when the iframe is ready to be added to the\n// * current page. It is responsible for determining where the iframe should\n// * be inserted in the DOM.\n// *\n// * @param error - Any error raised during the verification process;\n// * undefined if there is none.\n// * @param iframe - The iframe element containing the verification web page\n// * provided by the card issuer.\n// * @param cancel - A function, when called, will cancel the verification\n// * process and remove the iframe.\n// */\n// addFrame(\n// error: Error | undefined,\n// iframe: HTMLIFrameElement,\n// cancel: () => Promise | undefined,\n// ): void;\n//\n// /**\n// * A callback that gets called when the iframe is about to be removed from\n// * the current page.\n// */\n// removeFrame(): void;\n// }\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n commit?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => unknown): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\nexport type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreeVisaCheckout extends BraintreeModule {\n tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n createInitOptions(options: Partial): VisaCheckoutInitOptions;\n}\n\n/**\n *\n * Braintree Local Methods\n *\n */\nexport interface BraintreeLocalPaymentConfig {\n paymentType: string;\n amount: number;\n fallback: {\n url: string;\n buttonText: string;\n };\n currencyCode: string;\n shippingAddressRequired: boolean;\n email: string;\n givenName: string;\n surname: string;\n address: {\n countryCode: string;\n };\n onPaymentStart(data: BraintreeLPMPaymentStartData, start: () => Promise): Promise;\n}\n\nexport interface BraintreeLPMStartPaymentError {\n code: string;\n}\n\nexport interface BraintreeLPMPaymentStartData {\n paymentId: string;\n}\n\nexport interface BraintreeLocalPaymentsPayload {\n nonce: string;\n}\n\nexport interface BraintreeLocalPayment extends BraintreeModule {\n startPayment(\n config: BraintreeLocalPaymentConfig,\n callback: (\n startPaymentError: BraintreeLPMStartPaymentError | undefined,\n payload: BraintreeLocalPaymentsPayload,\n ) => Promise,\n ): void;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends BraintreeWindow {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n V?: VisaCheckoutSDK;\n}\n","import { BraintreeModuleName } from './braintree';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BraintreeModuleName.Client]:\n 'sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O',\n [BraintreeModuleName.Paypal]:\n 'sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT',\n [BraintreeModuleName.DataCollector]:\n 'sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT',\n [BraintreeModuleName.Venmo]:\n 'sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov',\n [BraintreeModuleName.HostedFields]:\n 'sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy',\n [BraintreeModuleName.Fastlane]:\n 'sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa',\n};\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\nimport { BRAINTREE_SDK_STABLE_VERSION } from './braintree-sdk-verison';\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeFastlaneCreator,\n BraintreeGooglePaymentCreator,\n BraintreeHostedFieldsCreator,\n BraintreeHostWindow,\n BraintreeLocalPaymentCreator,\n BraintreeModuleCreators,\n BraintreeModuleName,\n BraintreePaypalCheckoutCreator,\n BraintreePaypalCreator,\n BraintreeThreeDSecureCreator,\n BraintreeUsBankAccountCreator,\n BraintreeVenmoCheckoutCreator,\n BraintreeVisaCheckoutCreator,\n} from './types';\nimport { VisaCheckoutSDK } from './visacheckout';\n\nexport default class BraintreeScriptLoader {\n private braintreeSdkVersion = BRAINTREE_SDK_STABLE_VERSION;\n\n constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async loadClient(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Client,\n 'client.min.js',\n );\n }\n\n async loadFastlane(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Fastlane,\n 'fastlane.min.js',\n );\n }\n\n async loadPaypalCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.PaypalCheckout,\n 'paypal-checkout.min.js',\n );\n }\n\n async loadPaypal(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Paypal,\n 'paypal.min.js',\n );\n }\n\n async loadLocalPayment(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.LocalPayment,\n 'local-payment.min.js',\n );\n }\n\n async loadDataCollector(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.DataCollector,\n 'data-collector.min.js',\n );\n }\n\n async loadUsBankAccount(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.UsBankAccount,\n 'us-bank-account.min.js',\n );\n }\n\n async loadGooglePayment(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.GooglePayment,\n 'google-payment.min.js',\n );\n }\n\n async load3DS(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.ThreeDSecure,\n 'three-d-secure.min.js',\n );\n }\n\n loadVisaCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.VisaCheckout,\n 'visa-checkout.min.js',\n );\n }\n\n loadVenmoCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Venmo,\n 'venmo.min.js',\n );\n }\n\n async loadHostedFields(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.HostedFields,\n 'hosted-fields.min.js',\n );\n }\n\n async loadVisaCheckoutSdk(testMode?: boolean): Promise {\n if (this.braintreeHostWindow.V) {\n return this.braintreeHostWindow.V;\n }\n\n const hash = testMode\n ? 'sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm'\n : 'sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6';\n\n return this.scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n {\n async: true,\n attributes: {\n integrity: hash,\n crossorigin: 'anonymous',\n },\n },\n )\n .then(() => {\n if (!this.braintreeHostWindow.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.V;\n });\n }\n\n private async loadBraintreeModuleOrThrow(\n braintreeModuleName: BraintreeModuleName,\n fileName: string,\n ): Promise {\n let module = this.getBraintreeModule(braintreeModuleName);\n\n if (module) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return module as T;\n }\n\n const scriptPath = `//js.braintreegateway.com/web/${this.braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = this.getIntegrityValuesByModuleName(braintreeModuleName);\n\n await this.scriptLoader.loadScript(\n scriptPath,\n integrity\n ? {\n async: true,\n attributes: {\n integrity,\n crossorigin: 'anonymous',\n },\n }\n : undefined,\n );\n\n module = this.getBraintreeModule(braintreeModuleName);\n\n if (!module) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return module as T;\n }\n\n private getBraintreeModule(\n braintreeModuleName: BraintreeModuleName,\n ): BraintreeModuleCreators | undefined {\n return this.braintreeHostWindow.braintree?.[braintreeModuleName];\n }\n\n private getIntegrityValuesByModuleName(moduleName: BraintreeModuleName): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","export const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\n}\n","interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nfunction isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n\nexport default class ApplePaySessionFactory {\n create(request: ApplePayJS.ApplePayPaymentRequest): ApplePaySession {\n assertApplePayWindow(window);\n\n return new ApplePaySession(1, request);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n AddressRequestBody,\n Cart,\n Checkout,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport { WithApplePayCustomerInitializeOptions } from './apple-pay-customer-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _onAuthorizeCallback = noop;\n private _onError = noop;\n private _onClick = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _hasApplePaySession = false;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n container,\n shippingLabel,\n subtotalLabel,\n onError = noop,\n onClick = noop,\n onPaymentAuthorize,\n } = applepay;\n\n this._shippingLabel = shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = subtotalLabel || DefaultLabels.Subtotal;\n this._onAuthorizeCallback = onPaymentAuthorize;\n this._onError = onError;\n this._onClick = onClick;\n\n let state = this._paymentIntegrationService.getState();\n\n try {\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(methodId);\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(container);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n if (this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Apple, the shopper must click on \"Apple Pay\" button.',\n );\n }\n\n signOut(): Promise {\n throw new NotImplementedError('Need to do signout via apple.');\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private _createButton(containerId: string): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('button');\n\n button.setAttribute('type', 'button');\n button.setAttribute('aria-label', 'Apple Pay');\n container.appendChild(button);\n\n return button;\n }\n\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (this._hasApplePaySession) {\n return;\n }\n\n this._onClick();\n\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, config);\n\n applePaySession.begin();\n this._hasApplePaySession = true;\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n config: StoreConfig,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n this._onError(err);\n }\n };\n\n applePaySession.onshippingcontactselected = async (event) =>\n this._handleShippingContactSelected(applePaySession, config, event);\n\n applePaySession.onshippingmethodselected = async (event) =>\n this._handleShippingMethodSelected(applePaySession, config, event);\n\n applePaySession.oncancel = async () => {\n this._hasApplePaySession = false;\n\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n return this._onError(new PaymentMethodCancelledError());\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n this._hasApplePaySession = false;\n\n return this._onError(error);\n }\n\n const {\n storeProfile: { storeName },\n } = config;\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n return this._onError(error);\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n storeProfile: { storeName },\n } = config;\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n this._hasApplePaySession = false;\n\n return this._onError(error);\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return this._onError(error);\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n const state = this._paymentIntegrationService.getState();\n const braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayCustomerStrategy from './apple-pay-customer-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayCustomerStrategy, [{ id: 'applepay' }]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a payment method experiences some kind of\n * failure (i.e.: its client library returns a rejected promise). And there is\n * no other error type that is more specific than this one.\n */\nexport default class PaymentMethodFailedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method has thrown an unexpected error.',\n );\n\n this.name = 'PaymentMethodFailedError';\n this.type = 'payment_method_client_invalid';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if we are unable to successfully submit a server request\n * using a payment method because the method has invalid configuration or is in\n * an invalid state.\n */\nexport default class PaymentMethodInvalidError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'There is a problem processing your payment. Please try again later.',\n });\n\n this.name = 'PaymentMethodInvalidError';\n this.type = 'payment_method_invalid';\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n CheckoutPaymentMethodExecutedOptions,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n isCustomError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltCheckout, BoltHostWindow, BoltInitializationData } from './bolt';\nimport { WithBoltCustomerInitializeOptions } from './bolt-customer-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltCustomerStrategy implements CustomerStrategy {\n private boltHostWindow: BoltHostWindow = window;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBoltCustomerInitializeOptions,\n ): Promise {\n const { methodId, bolt } = options;\n const { onInit } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData?.publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { developerConfig, publishableKey } = paymentMethod.initializationData;\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n paymentMethod.config.testMode,\n developerConfig,\n );\n\n if (onInit && typeof onInit === 'function') {\n const email = this.getCustomerEmail();\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n onInit(hasBoltAccount, email);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const {\n continueWithCheckoutCallback = noop,\n checkoutPaymentMethodExecuted,\n methodId,\n } = options || {};\n const email = this.getCustomerEmail();\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n if (!email) {\n continueWithCheckoutCallback();\n\n return;\n }\n\n return this.openBoltCheckoutModalOrThrow(\n email,\n methodId,\n continueWithCheckoutCallback,\n checkoutPaymentMethodExecuted,\n );\n }\n\n private async openBoltCheckoutModalOrThrow(\n email: string,\n methodId: string,\n continueWithCheckoutCallback: () => void,\n checkoutPaymentMethodExecuted?: (payload: CheckoutPaymentMethodExecutedOptions) => void,\n ): Promise {\n const boltClient = this.getBoltClientOrThrow();\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n try {\n if (paymentMethod?.initializationData?.embeddedOneClickEnabled) {\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n if (hasBoltAccount) {\n const callbacks = {\n close: () => {\n continueWithCheckoutCallback();\n },\n };\n\n await boltClient.openCheckout(email, callbacks);\n } else {\n continueWithCheckoutCallback();\n }\n\n if (typeof checkoutPaymentMethodExecuted === 'function') {\n checkoutPaymentMethodExecuted({ hasBoltAccount });\n }\n } else {\n continueWithCheckoutCallback();\n }\n } catch (error) {\n if (\n isCustomError(error) &&\n error.name !== 'MissingDataError' &&\n error.name !== 'NotInitializedError'\n ) {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n const boltClient = this.boltHostWindow.BoltCheckout;\n\n if (!boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return boltClient;\n }\n\n private async hasBoltAccount(email: string) {\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private getCustomerEmail() {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n\n return customer?.email || billingAddress?.email || '';\n }\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: any): error is CustomError {\n return (\n typeof error.message === 'string' &&\n typeof error.type === 'string' &&\n (typeof error.subtype === 'string' || !error.subtype) &&\n error instanceof Error\n );\n}\n","import {\n BuyNowCartRequestBody,\n NonceInstrument,\n PaymentMethod,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface BoltHostWindow extends Window {\n BoltCheckout?: BoltCheckout;\n BoltConnect?: BoltConnect;\n Bolt?(publicKey: string): BoltEmbedded;\n}\n\nexport interface BoltCheckout {\n configure(cart: BoltCart, hints: Record, callbacks?: BoltCallbacks): BoltClient;\n hasBoltAccount(email: string): Promise;\n getTransactionReference(): Promise;\n openCheckout(email: string, callbacks?: BoltOpenCheckoutCallbacks): Promise;\n setClientCustomCallbacks(callbacks: BoltCallbacks): void;\n setOrderId(orderId: number): Promise;\n}\n\nexport interface BoltConnect {\n setupProductPageCheckout?(): void;\n}\n\nexport interface BoltOpenCheckoutCallbacks {\n close?(): void;\n}\n\nexport interface BoltEmbeddedOptions {\n styles: { backgroundColor: string };\n renderSeparateFields?: boolean;\n}\n\nexport interface BoltEmbedded {\n create(name: string, options?: BoltEmbeddedOptions): BoltEmbededField;\n}\n\nexport interface BoltEmbededField {\n mount(element: string): void;\n unmount(): void;\n tokenize(): Promise;\n}\n\nexport interface BoltDeveloperModeParams {\n developerMode: BoltDeveloperMode;\n developerDomain: string;\n}\n\nexport enum BoltDeveloperMode {\n SandboxMode = 'bolt_sandbox',\n StagingMode = 'bolt_staging',\n DevelopmentMode = 'bolt_development',\n}\n\nexport interface BoltClient {\n open(): void;\n}\n\nexport interface BoltCart {\n orderToken: string;\n}\n\nexport interface BoltCallbacks {\n check?(): boolean;\n onCheckoutStart?(): void;\n onPaymentSubmit?(): void;\n success(transaction: BoltTransaction, callback: () => void): void;\n close?(): void;\n}\n\nexport interface BoltTransaction {\n id: string;\n type: string;\n processor: string;\n date: number;\n reference: string;\n status: string;\n authorization: BoltAuthorization;\n}\n\nexport interface BoltAuthorization {\n status: string;\n reason: string;\n}\n\nexport interface BoltEmbeddedTokenize {\n bin: string;\n expiration: string;\n last4: string;\n postal_code?: string;\n token: string;\n token_type: string;\n}\n\nexport interface BoltPaymentMethod extends PaymentMethod {\n initializationData?: BoltInitializationData;\n}\n\nexport interface BoltInitializationData {\n publishableKey: string;\n developerConfig: BoltDeveloperModeParams;\n embeddedOneClickEnabled: boolean;\n}\n\nexport type BoltPaymentData = WithAccountCreation & NonceInstrument;\n\nexport interface BoltBuyNowInitializeOptions {\n storefrontApiToken?: string;\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\nexport enum StyleButtonSize {\n Small = 'small',\n Medium = 'medium',\n Large = 'large',\n}\n\nexport enum StyleButtonShape {\n Pill = 'pill',\n Rect = 'rect',\n}\n\nexport interface BoltButtonStyleOptions {\n shape?: StyleButtonShape;\n size?: StyleButtonSize;\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n InvalidArgumentError,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltDeveloperMode,\n BoltDeveloperModeParams,\n BoltEmbedded,\n BoltHostWindow,\n} from './bolt';\n\nexport default class BoltScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async loadBoltClient(\n publishableKey?: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n cartId?: string,\n storefrontApiToken?: string,\n ): Promise {\n if (this.boltHostWindow.BoltCheckout) {\n return this.boltHostWindow.BoltCheckout;\n }\n\n if (!publishableKey) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publishableKey\" argument is not provided.',\n );\n }\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/connect-bigcommerce.js`,\n this.getScriptOptions('bolt-connect', publishableKey, cartId, storefrontApiToken),\n );\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/track.js`,\n this.getScriptOptions('bolt-track', publishableKey),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this.boltHostWindow.BoltCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.BoltCheckout;\n }\n\n async loadBoltEmbedded(\n publishableKey: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n ): Promise {\n const options: LoadScriptOptions = {\n async: true,\n attributes: {\n id: 'bolt-embedded',\n },\n };\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/embed.js`,\n options,\n );\n\n if (!this.boltHostWindow.Bolt) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.Bolt(publishableKey);\n }\n\n getDomainURL(testMode: boolean, developerModeParams?: BoltDeveloperModeParams): string {\n if (!testMode) {\n return 'connect.bolt.com';\n }\n\n if (developerModeParams) {\n switch (developerModeParams.developerMode) {\n case BoltDeveloperMode.StagingMode:\n return 'connect-staging.bolt.com';\n\n case BoltDeveloperMode.DevelopmentMode:\n return `connect.${developerModeParams.developerDomain}`;\n }\n }\n\n return 'connect-sandbox.bolt.com';\n }\n\n private getScriptOptions(\n id: string,\n publishableKey: string,\n cartId?: string,\n storefrontApiToken?: string,\n ): LoadScriptOptions {\n return {\n async: true,\n attributes: {\n id,\n 'data-publishable-key': publishableKey,\n ...(cartId && { 'data-shopping-cart-id': cartId }),\n ...(storefrontApiToken && { 'data-storefront-api-token': storefrontApiToken }),\n },\n };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltCustomerStrategy from './bolt-customer-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltCustomerStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltCustomerStrategy, [{ id: 'bolt' }]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/form-poster\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@braintree/browser-detection\");","// the PayPal side of things uses uppercase keys instead of camel case\n\n/**\n *\n * PayPal constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n WHITE = 'white',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\n/**\n *\n * PayPal interfaces\n *\n */\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface MessagingOptions {\n amount: number;\n buyerCountry?: string;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface MessagesStyleOptions {\n layout?: 'text' | 'flex';\n logo?: {\n type: 'none' | 'inline' | 'primary';\n };\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onClick?(): void;\n onCancel?(): void;\n onError?(error: Error): void;\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n close(): void;\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n","import { supportsPopups } from '@braintree/browser-detection';\n\nimport {\n Address,\n LegacyAddress,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig,\n BraintreeDataCollectors,\n BraintreeEnv,\n BraintreeError,\n BraintreeFastlane,\n BraintreeFastlaneStylesOption,\n BraintreeHostWindow,\n BraintreeModule,\n BraintreePaypal,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeShippingAddressOverride,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n PAYPAL_COMPONENTS,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\n\nexport interface PaypalConfig {\n amount: number;\n currency: string;\n locale: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n shouldSaveInstrument?: boolean;\n}\n\n// Info: this class is deprecated and will be removed in a nearest future. Please, do not add anything here.\nexport default class BraintreeIntegrationService {\n private client?: Promise;\n private clientToken?: string;\n private dataCollectors: BraintreeDataCollectors = {};\n private paypalCheckout?: BraintreePaypalCheckout;\n private braintreePaypal?: Promise;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string) {\n this.clientToken = clientToken;\n }\n\n async getBraintreeFastlane(\n cardId?: string,\n isTestModeEnabled?: boolean,\n styles?: BraintreeFastlaneStylesOption,\n ): Promise {\n if (isTestModeEnabled) {\n window.localStorage.setItem('axoEnv', 'sandbox');\n window.localStorage.setItem('fastlaneEnv', 'sandbox');\n }\n\n if (!this.braintreeHostWindow.braintreeFastlane) {\n const clientToken = this.getClientTokenOrThrow();\n const client = await this.getClient();\n const deviceData = await this.getSessionId(cardId);\n\n const braintreeFastlaneCreator = await this.braintreeScriptLoader.loadFastlane();\n\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.braintreeHostWindow.braintreeFastlane = await braintreeFastlaneCreator.create({\n authorization: clientToken,\n client,\n deviceData,\n styles: styles || defaultStyles,\n });\n }\n\n return this.braintreeHostWindow.braintreeFastlane;\n }\n\n // Info: This method is deprecated. Use getClient method from BraintreeSdk class instead\n async getClient(): Promise {\n if (!this.client) {\n const clientToken = this.getClientTokenOrThrow();\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = clientCreator.create({ authorization: clientToken });\n }\n\n return this.client;\n }\n\n getPaypal(): Promise {\n if (!this.braintreePaypal) {\n this.braintreePaypal = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadPaypal(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this.braintreePaypal;\n }\n\n paypal({ shouldSaveInstrument, ...config }: PaypalConfig): Promise {\n const newWindowFlow = supportsPopups();\n\n return this.getPaypal()\n .then((paypal) => {\n if (newWindowFlow) {\n this.overlay?.show({\n onClick: () => paypal.focusWindow(),\n });\n }\n\n return paypal.tokenize({\n enableShippingAddress: true,\n flow: shouldSaveInstrument ? 'vault' : 'checkout',\n useraction: 'commit',\n ...config,\n });\n })\n .then((response) => {\n this.overlay?.remove();\n\n return response;\n })\n .catch((error) => {\n this.overlay?.remove();\n\n throw error;\n });\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this.braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError | undefined,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n commit: config.commit ?? true,\n };\n\n if (!this.braintreeHostWindow.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this.paypalCheckout = await paypalCheckout.create(\n paypalCheckoutConfig,\n paypalCheckoutCallback,\n );\n\n return this.paypalCheckout;\n }\n\n async getDataCollector(\n options?: Partial,\n ): Promise {\n const cacheKey: keyof BraintreeDataCollectors = options?.paypal ? 'paypal' : 'default';\n\n let cached = this.dataCollectors[cacheKey];\n\n if (!cached) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n const dataCollectorConfig: BraintreeDataCollectorCreatorConfig = {\n client,\n kount: true,\n ...options,\n };\n\n cached = await dataCollector.create(dataCollectorConfig);\n } catch (error) {\n if (isBraintreeError(error) && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n cached = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n } else {\n throw error;\n }\n }\n\n this.dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getBraintreeEnv(isTestMode = false): BraintreeEnv {\n return isTestMode ? BraintreeEnv.Sandbox : BraintreeEnv.Production;\n }\n\n mapToBraintreeShippingAddressOverride(address: Address): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n }\n\n mapToLegacyShippingAddress(details: BraintreeTokenizationDetails): Partial {\n const { email, phone, shippingAddress } = details;\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n }\n\n mapToLegacyBillingAddress(details: BraintreeTokenizationDetails): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n }\n\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n async getSessionId(cartId?: string): Promise {\n const { deviceData } = await this.getDataCollector({\n riskCorrelationId: cartId,\n });\n\n return deviceData;\n }\n\n async teardown(): Promise {\n await this.teardownModule(this.dataCollectors.default);\n await this.teardownModule(this.dataCollectors.paypal);\n this.dataCollectors = {};\n\n await this.teardownModule(this.paypalCheckout);\n this.paypalCheckout = undefined;\n\n // await this.teardownModule(this._venmoCheckout);\n // this._venmoCheckout = undefined;\n\n // await this.teardownModule(this._visaCheckout);\n // this._visaCheckout = undefined;\n }\n\n private teardownModule(module?: BraintreeModule) {\n return module ? module.teardown() : Promise.resolve();\n }\n\n private getClientTokenOrThrow(): string {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.clientToken;\n }\n}\n","const DefaultCheckoutButtonHeight = 36;\n\nexport default DefaultCheckoutButtonHeight;\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCustomerInitializeOptions, {\n WithBraintreePaypalCustomerInitializeOptions,\n} from './braintree-paypal-customer-initialize-options';\n\nexport default class BraintreePaypalCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypal, methodId } = options;\n const { container, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.container\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n const { clientToken, config, initializationData } = paymentMethod;\n const { paymentButtonStyles } = initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n methodId,\n Boolean(config.testMode),\n checkoutTopButtonStyles,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonStyles: PaypalStyleOptions,\n ): void {\n const { container, onClick = noop } = braintreepaypal;\n\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const paypalButtonRender = paypal.Buttons({\n env: this.braintreeIntegrationService.getBraintreeEnv(testMode),\n fundingSource,\n style: { ...buttonStyles, height: DefaultCheckoutButtonHeight },\n createOrder: () =>\n this.setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypal,\n ),\n onClick,\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n }\n } else {\n this.braintreeIntegrationService.removeElement(container);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCustomerStrategy from './braintree-paypal-customer-strategy';\n\nconst createBraintreePaypalCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCustomerStrategy, [\n { id: 'braintreepaypal' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditCustomerInitializeOptions, {\n WithBraintreePaypalCreditCustomerInitializeOptions,\n} from './braintree-paypal-credit-customer-options';\n\nexport default class BraintreePaypalCreditCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCreditCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypalcredit, methodId } = options;\n const { container, onError } = braintreepaypalcredit || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.container\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n const { clientToken, config, initializationData } = paymentMethod;\n const { paymentButtonStyles } = initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n Boolean(config.testMode),\n { ...checkoutTopButtonStyles, height: DefaultCheckoutButtonHeight },\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonStyles: PaypalStyleOptions,\n ): void {\n const { container, onClick = noop } = braintreepaypalcredit;\n const { paypal } = this.braintreeHostWindow;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: buttonStyles,\n createOrder: () =>\n this.setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypalcredit,\n ),\n onClick,\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this.braintreeIntegrationService.removeElement(container);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypalcredit;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypalcredit;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditCustomerStrategy from './braintree-paypal-credit-customer-strategy';\n\nconst createBraintreePaypalCreditCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCreditCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCreditCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditCustomerStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"local-storage-fallback\");","import LocalStorage from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = LocalStorage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return LocalStorage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return LocalStorage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this.namespace}.${key}`;\n }\n}\n","import { omitBy } from 'lodash';\n\nimport { BraintreeFastlaneStylesOption, FastlaneStylesSettings } from '../index';\n\nfunction isInvalidStyleOption(styleOption: unknown) {\n return typeof styleOption !== 'string';\n}\n\nexport default function getFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: BraintreeFastlaneStylesOption,\n): BraintreeFastlaneStylesOption | undefined {\n if (!uiStyles && !styleSettings) {\n return undefined;\n }\n\n return cleanUpFastlaneStyles(mergeFastlaneStyles(styleSettings, uiStyles));\n}\n\nfunction mergeFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: BraintreeFastlaneStylesOption,\n): BraintreeFastlaneStylesOption {\n return {\n root: {\n backgroundColorPrimary:\n styleSettings?.fastlaneRootSettingsBackgroundColor ||\n uiStyles?.root?.backgroundColorPrimary,\n errorColor: styleSettings?.fastlaneRootSettingsErrorColor || uiStyles?.root?.errorColor,\n fontFamily: styleSettings?.fastlaneRootSettingsFontFamily || uiStyles?.root?.fontFamily,\n fontSizeBase:\n styleSettings?.fastlaneRootSettingsFontSize || uiStyles?.root?.fontSizeBase,\n padding: styleSettings?.fastlaneRootSettingsPadding || uiStyles?.root?.padding,\n primaryColor:\n styleSettings?.fastlaneRootSettingsPrimaryColor || uiStyles?.root?.primaryColor,\n },\n input: {\n borderRadius:\n styleSettings?.fastlaneInputSettingsBorderRadius || uiStyles?.input?.borderRadius,\n borderColor:\n styleSettings?.fastlaneInputSettingsBorderColor || uiStyles?.input?.borderColor,\n focusBorderColor:\n styleSettings?.fastlaneInputSettingsFocusBorderBase ||\n uiStyles?.input?.focusBorderColor,\n backgroundColor:\n styleSettings?.fastlaneInputSettingsBackgroundColor ||\n uiStyles?.input?.backgroundColor,\n borderWidth:\n styleSettings?.fastlaneInputSettingsBorderWidth || uiStyles?.input?.borderWidth,\n textColorBase:\n styleSettings?.fastlaneInputSettingsTextColorBase || uiStyles?.input?.textColorBase,\n },\n toggle: {\n colorPrimary:\n styleSettings?.fastlaneToggleSettingsColorPrimary || uiStyles?.toggle?.colorPrimary,\n colorSecondary:\n styleSettings?.fastlaneToggleSettingsColorSecondary ||\n uiStyles?.toggle?.colorSecondary,\n },\n text: {\n body: {\n color: styleSettings?.fastlaneTextBodySettingsColor || uiStyles?.text?.body?.color,\n fontSize:\n styleSettings?.fastlaneTextBodySettingsFontSize ||\n uiStyles?.text?.body?.fontSize,\n },\n caption: {\n color:\n styleSettings?.fastlaneTextCaptionSettingsColor ||\n uiStyles?.text?.caption?.color,\n fontSize:\n styleSettings?.fastlaneTextCaptionSettingsFontSize ||\n uiStyles?.text?.caption?.fontSize,\n },\n },\n branding: styleSettings?.fastlaneBrandingSettings || uiStyles?.branding,\n };\n}\n\nfunction cleanUpFastlaneStyles(styles: BraintreeFastlaneStylesOption) {\n const fastlaneStyles: BraintreeFastlaneStylesOption = {};\n\n const root = omitBy(styles.root, isInvalidStyleOption);\n const input = omitBy(styles.input, isInvalidStyleOption);\n const toggle = omitBy(styles.toggle, isInvalidStyleOption);\n const textBody = omitBy(styles.text?.body, isInvalidStyleOption);\n const textCaption = omitBy(styles.text?.caption, isInvalidStyleOption);\n const branding = styles.branding;\n\n if (Object.keys(root).length) {\n fastlaneStyles.root = root;\n }\n\n if (Object.keys(input).length) {\n fastlaneStyles.input = input;\n }\n\n if (Object.keys(toggle).length) {\n fastlaneStyles.toggle = toggle;\n }\n\n if (Object.keys(textBody).length) {\n fastlaneStyles.text = {};\n fastlaneStyles.text.body = textBody;\n }\n\n if (Object.keys(textCaption).length) {\n fastlaneStyles.text = {\n ...fastlaneStyles.text,\n };\n fastlaneStyles.text.caption = textCaption;\n }\n\n if (branding) {\n fastlaneStyles.branding = branding;\n }\n\n return fastlaneStyles;\n}\n","import {\n BraintreeInitializationData,\n getFastlaneStyles,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeFastlaneCustomerInitializeOptions } from './braintree-fastlane-customer-initialize-options';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nexport default class BraintreeFastlaneCustomerStrategy implements CustomerStrategy {\n private isAcceleratedCheckoutEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n ) {}\n\n async initialize({\n methodId,\n braintreefastlane,\n }: CustomerInitializeOptions & WithBraintreeFastlaneCustomerInitializeOptions): Promise {\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = await this.getValidPaymentMethodOrThrow(methodId);\n\n const { isAcceleratedCheckoutEnabled, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n const paypalFastlaneStylesSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\n\n this.isAcceleratedCheckoutEnabled = !!isAcceleratedCheckoutEnabled;\n\n try {\n if (this.isAcceleratedCheckoutEnabled) {\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStylesSettings,\n braintreefastlane?.styles,\n );\n\n await this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(\n paymentMethod.id,\n fastlaneStyles,\n );\n }\n } catch (_) {\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n\n return Promise.resolve();\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const { checkoutPaymentMethodExecuted, continueWithCheckoutCallback } = options || {};\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomerOrThrow();\n\n if (this.isAcceleratedCheckoutEnabled && customer.isGuest) {\n const shouldRunAuthenticationFlow = await this.shouldRunAuthenticationFlow();\n\n if (\n checkoutPaymentMethodExecuted &&\n typeof checkoutPaymentMethodExecuted === 'function'\n ) {\n checkoutPaymentMethodExecuted();\n }\n\n if (shouldRunAuthenticationFlow) {\n await this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(\n undefined,\n true,\n );\n }\n }\n\n continueWithCheckoutCallback();\n }\n\n // TODO: remove this method after A/B testing finished\n private async shouldRunAuthenticationFlow(): Promise {\n const primaryMethodId = 'braintreeacceleratedcheckout';\n\n try {\n // Info: we should load payment method each time to detect if the user\n // should be in a test or in a control group\n await this.paymentIntegrationService.loadPaymentMethod(primaryMethodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(primaryMethodId);\n\n // Info: shouldRunAcceleratedCheckout is responsible for the flow of A/B testing purposes\n // when shouldRunAcceleratedCheckout is true, the lookup PayPal Connect method should be called,\n // otherwise AcceleratedCheckout should not be available for the customer\n return paymentMethod.initializationData?.shouldRunAcceleratedCheckout || false;\n } catch (_) {\n return false;\n }\n }\n\n private async getValidPaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n let validPaymentMethodId = methodId;\n\n try {\n await this.paymentIntegrationService.loadPaymentMethod(validPaymentMethodId);\n } catch {\n validPaymentMethodId =\n methodId === 'braintree' ? 'braintreeacceleratedcheckout' : 'braintree';\n await this.paymentIntegrationService.loadPaymentMethod(validPaymentMethodId);\n }\n\n return this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(validPaymentMethodId);\n }\n}\n","type PaymentInstrument = CardInstrument | AccountInstrument;\n\nexport default PaymentInstrument;\n\ninterface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport enum UntrustedShippingCardVerificationType {\n CVV = 'cvv',\n PAN = 'pan',\n}\n\nexport interface CardInstrument extends BaseInstrument {\n brand: string;\n expiryMonth: string;\n expiryYear: string;\n iin: string;\n last4: string;\n type: 'card';\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType;\n}\n\ninterface BaseAccountInstrument extends BaseInstrument {\n method: string;\n type: 'account' | 'bank';\n}\n\nexport interface PayPalInstrument extends BaseAccountInstrument {\n externalId: string;\n method: 'paypal';\n}\n\nexport interface AchInstrument extends BaseAccountInstrument {\n issuer: string;\n accountNumber: string;\n type: 'bank';\n method: 'ach' | 'ecp';\n}\n\nexport interface BankInstrument extends BaseAccountInstrument {\n accountNumber: string;\n issuer: string;\n iban: string;\n method: string;\n type: 'bank';\n}\n\nexport type AccountInstrument = PayPalInstrument | BankInstrument | AchInstrument;\n\nexport interface VaultAccessToken {\n vaultAccessToken: string;\n vaultAccessExpiry: number;\n}\n\nexport interface SessionContext {\n customerId: number;\n storeId: string;\n currencyCode?: string;\n}\n\nexport interface InstrumentRequestContext extends SessionContext {\n authToken: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlane,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CardInstrument,\n CustomerAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n UntrustedShippingCardVerificationType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nexport default class BraintreeFastlaneUtils {\n private braintreeFastlane?: BraintreeFastlane;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private browserStorage: BrowserStorage,\n ) {}\n\n async getDeviceSessionId(): Promise {\n const cart = this.paymentIntegrationService.getState().getCart();\n\n return this.braintreeIntegrationService.getSessionId(cart?.id);\n }\n\n /**\n *\n * Initialization method\n *\n */\n async initializeBraintreeFastlaneOrThrow(\n methodId: string,\n styles?: BraintreeFastlaneStylesOption,\n ) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCart();\n const { clientToken, config } =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.methodId = methodId;\n\n this.braintreeIntegrationService.initialize(clientToken);\n\n this.braintreeFastlane = await this.braintreeIntegrationService.getBraintreeFastlane(\n cart?.id,\n config.testMode,\n styles,\n );\n }\n\n getBraintreeFastlaneOrThrow(): BraintreeFastlane {\n if (!this.braintreeFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeFastlane;\n }\n\n getBraintreeFastlaneComponentOrThrow(): BraintreeFastlane['FastlaneCardComponent'] {\n const braintreeFastlane = this.getBraintreeFastlaneOrThrow();\n\n return braintreeFastlane.FastlaneCardComponent;\n }\n\n /**\n *\n * Authentication methods\n *\n * */\n // Remove this rule disabling after method refactor\n // eslint-disable-next-line complexity\n async runPayPalAuthenticationFlowOrThrow(\n email?: string,\n shouldSetShippingOption?: boolean,\n ): Promise {\n try {\n const methodId = this.getMethodIdOrThrow();\n const braintreeFastlane = this.getBraintreeFastlaneOrThrow();\n const { lookupCustomerByEmail, triggerAuthenticationFlow } = braintreeFastlane.identity;\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const { isFastlaneShippingOptionAutoSelectEnabled } =\n state.getPaymentMethodOrThrow(methodId)\n .initializationData || {};\n\n const customerEmail = email || customer?.email || billingAddress?.email || '';\n\n const { customerContextId } = await lookupCustomerByEmail(customerEmail);\n\n if (!customerContextId) {\n // Info: we should clean up previous experience with default data and related authenticationState\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: BraintreeFastlaneAuthenticationState.UNRECOGNIZED,\n addresses: [],\n instruments: [],\n });\n\n this.browserStorage.setItem('sessionId', cart.id);\n\n return;\n }\n\n const { authenticationState, profileData } = await triggerAuthenticationFlow(\n customerContextId,\n );\n\n const phoneNumber = profileData?.shippingAddress?.phoneNumber || '';\n\n if (authenticationState === BraintreeFastlaneAuthenticationState.CANCELED) {\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses: [],\n instruments: [],\n });\n\n this.browserStorage.removeItem('sessionId');\n\n return;\n }\n\n const shippingAddresses =\n this.mapPayPalToBcAddress([profileData.shippingAddress], [phoneNumber]) || [];\n const paypalBillingAddress = this.getPayPalBillingAddresses(profileData);\n const billingAddresses = paypalBillingAddress\n ? this.mapPayPalToBcAddress([paypalBillingAddress], [phoneNumber])\n : [];\n const instruments = profileData.card\n ? this.mapPayPalToBcInstrument(methodId, [profileData.card])\n : [];\n const addresses = this.mergeShippingAndBillingAddresses(\n shippingAddresses,\n billingAddresses,\n );\n\n this.browserStorage.setItem('sessionId', cart.id);\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n if (billingAddresses.length > 0 && cart.lineItems.physicalItems.length > 0) {\n await this.paymentIntegrationService.updateBillingAddress(billingAddresses[0]);\n }\n\n // Prefill billing form if only digital items in cart with billing data and firstName and lastName\n // from shippingAddresses because there are empty in billing\n if (\n billingAddresses.length > 0 &&\n cart.lineItems.digitalItems.length > 0 &&\n cart.lineItems.physicalItems.length === 0\n ) {\n const { firstName, lastName } = addresses[0];\n const digitalItemBilling = {\n ...billingAddresses[0],\n firstName,\n lastName,\n };\n\n await this.paymentIntegrationService.updateBillingAddress(digitalItemBilling);\n }\n\n if (shippingAddresses.length > 0 && cart.lineItems.physicalItems.length > 0) {\n await this.paymentIntegrationService.updateShippingAddress(shippingAddresses[0]);\n\n if (shouldSetShippingOption && isFastlaneShippingOptionAutoSelectEnabled) {\n await this.setShippingOption();\n }\n }\n } catch (error) {\n // TODO: we should figure out what to do here\n // TODO: because we should not to stop the flow if the error occurs on paypal side\n }\n }\n\n /**\n *\n * PayPal to BC data mappers\n *\n * */\n mapPayPalToBcInstrument(\n methodId: string,\n instruments?: BraintreeFastlaneVaultedInstrument[],\n ): CardInstrument[] | undefined {\n if (!instruments) {\n return;\n }\n\n return instruments.map((instrument) => {\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n type: 'card',\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.PAN,\n };\n });\n }\n\n private mapPayPalToBcAddress(\n addresses?: BraintreeFastlaneAddress[],\n phones?: string[],\n ): CustomerAddress[] {\n if (!addresses) {\n return [];\n }\n\n const countries = this.paymentIntegrationService.getState().getCountries() || [];\n\n const getCountryNameByCountryCode = (countryCode: string) => {\n const matchedCountry = countries.find((country) => country.code === countryCode);\n\n return matchedCountry?.name || '';\n };\n\n return addresses.map((address) => ({\n id: Date.now(),\n type: 'paypal-address',\n firstName: address.firstName || '',\n lastName: address.lastName || '',\n company: address.company || '',\n address1: address.streetAddress,\n address2: address.extendedAddress || '',\n city: address.locality,\n stateOrProvince: address.region,\n stateOrProvinceCode: address.region,\n country: getCountryNameByCountryCode(address.countryCodeAlpha2),\n countryCode: address.countryCodeAlpha2,\n postalCode: address.postalCode,\n phone: (phones && phones[0]) || '',\n customFields: [],\n }));\n }\n\n /**\n *\n * Get PayPal billing addresses from stored braintree instruments info\n *\n * */\n private getPayPalBillingAddresses(\n profileData?: BraintreeFastlaneProfileData,\n ): BraintreeFastlaneAddress | undefined {\n const { card, name } = profileData || {};\n\n if (!card) {\n return;\n }\n\n const { firstName, lastName } = card.paymentSource.card.billingAddress;\n const { firstName: given_name, lastName: surname } = name || {};\n const { shippingAddress } = profileData || {};\n const address = {\n ...card.paymentSource.card.billingAddress,\n firstName: firstName || given_name,\n lastName: lastName || surname,\n };\n\n const isAddressExist =\n shippingAddress &&\n isEqual(this.normalizeAddress(address), this.normalizeAddress(shippingAddress));\n\n return isAddressExist ? shippingAddress : address;\n }\n\n private normalizeAddress(address: CustomerAddress | BraintreeFastlaneAddress) {\n return omit(address, ['id']);\n }\n\n private mergeShippingAndBillingAddresses(\n shippingAddresses: CustomerAddress[],\n billingAddresses: CustomerAddress[],\n ): CustomerAddress[] {\n const filteredBillingAddresses = billingAddresses.filter(\n (billingAddress: CustomerAddress) =>\n !shippingAddresses.some((shippingAddress: CustomerAddress) => {\n return isEqual(\n this.normalizeAddress(shippingAddress),\n this.normalizeAddress(billingAddress),\n );\n }),\n );\n\n return [...shippingAddresses, ...filteredBillingAddresses];\n }\n\n /**\n *\n * Other\n *\n * */\n private getMethodIdOrThrow(): string {\n if (!this.methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n return this.methodId;\n }\n\n private async setShippingOption(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments() || [];\n const availableShippingOptions = consignments[0]?.availableShippingOptions || [];\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n if (recommendedShippingOption || availableShippingOptions.length) {\n const selectedOption = recommendedShippingOption || availableShippingOptions[0];\n\n await this.paymentIntegrationService.selectShippingOption(selectedOption.id);\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport BraintreeFastlaneCustomerStrategy from './braintree-fastlane-customer-strategy';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nconst createBraintreeFastlaneCustomerStrategy: CustomerStrategyFactory<\n BraintreeFastlaneCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n const browserStorage = new BrowserStorage('paypalFastlane');\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n browserStorage,\n );\n\n return new BraintreeFastlaneCustomerStrategy(paymentIntegrationService, braintreeFastlaneUtils);\n};\n\n// Info: braintree method id was added only for A/B testing purposes.\n// The main reason why we can't go in other way, because braintreeacceleratedcheckout\n// may be turned on only when BE knows customer's email address (to understand should we show the feature for the user or not).\n// So { id: 'braintree' }, should be removed after A/B testing\nexport default toResolvableModule(createBraintreeFastlaneCustomerStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n { id: 'braintree' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutCustomerInitializeOptions } from './braintree-visa-customer-initialize-options';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private buttonClassName = 'visa-checkout-wrapper';\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreeVisaCheckoutCustomerInitializeOptions,\n ): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const checkout = state.getCheckoutOrThrow();\n\n const { clientToken, config } = state.getPaymentMethodOrThrow(methodId);\n\n const storeConfig = state.getStoreConfigOrThrow();\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutInstance = await this.braintreeSdk.getVisaCheckoutSdk(config.testMode);\n\n const { container, onError } = visaCheckoutOptions;\n\n this.onError = onError || noop;\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: true,\n },\n },\n });\n\n const signInButton = this.createSignInButton(container, this.buttonClassName);\n\n await visaCheckoutInstance.init(initOptions);\n\n visaCheckoutInstance.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() => this.paymentIntegrationService.loadCheckout())\n .catch((error) => this.handleError(error)),\n );\n\n visaCheckoutInstance.on('payment.error', (_, error) => this.handleError(error));\n\n signInButton.style.visibility = 'visible';\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private async tokenizePayment(\n braintreeVisaCheckout: BraintreeVisaCheckout,\n payment: VisaCheckoutPaymentSuccessPayload,\n ) {\n return Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this.braintreeSdk.getDataCollectorOrThrow(),\n ]).then(([payload, deviceData]) => {\n const state = this.paymentIntegrationService.getState();\n\n const shipping = state.getShippingAddress();\n const billing = state.getBillingAddress();\n\n const {\n shippingAddress = this.mapToVisaCheckoutAddress(shipping),\n billingAddress = this.mapToVisaCheckoutAddress(billing),\n } = payload;\n\n return this.postForm(\n {\n ...payload,\n shippingAddress,\n billingAddress,\n },\n deviceData,\n );\n });\n }\n\n private postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: JSON.stringify({\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n }),\n billing_address: JSON.stringify(this.getAddress(userEmail, billingAddress)),\n shipping_address: JSON.stringify(this.getAddress(userEmail, shippingAddress)),\n });\n }\n\n private mapToVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Unable to proceed because the provided container ID is not valid.');\n }\n\n return this.insertVisaCheckoutButton(container, buttonClass);\n }\n\n private insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.style.width = 'max-content';\n\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutCustomerStrategy from './braintree-visa-checkout-customer-strategy';\n\nconst createBraintreeVisaCheckoutCustomerStrategy: CustomerStrategyFactory<\n BraintreeVisaCheckoutCustomerStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), hostWindow));\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","/**\n * Decorates a class or a method by binding all its prototype methods or itself\n * to the calling instance respectively.\n */\nfunction bindDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor;\nfunction bindDecorator>(target: T): T;\n\nfunction bindDecorator(target: any, key?: any, descriptor?: any): any {\n if (!key || !descriptor) {\n return bindClassDecorator(target);\n }\n\n return bindMethodDecorator(target, key, descriptor);\n}\n\nexport default bindDecorator;\n\n/**\n * Decorates a class by binding all its prototype methods to the calling\n * instance.\n */\nexport function bindClassDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n bindMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\n/**\n * Decorates a method by binding it to the calling instance.\n */\nexport function bindMethodDecorator(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let method: T = descriptor.value;\n\n return {\n get() {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const boundMethod = method.bind(this) as T;\n\n Object.defineProperty(this, key, {\n ...descriptor,\n value: boundMethod,\n });\n\n return boundMethod;\n },\n set(value) {\n method = value;\n },\n };\n}\n\nexport type Constructor = new (...args: any[]) => T;\nexport type Method = (...args: any[]) => any;\n","import { InvalidArgumentError } from '../errors';\n\nimport { CurrencyConfig } from './currency';\n\nexport default class CurrencyFormatter {\n private _decimalPlaces: number;\n private _symbolLocation: string;\n private _symbol: string;\n private _thousandsSeparator: string;\n private _decimalSeparator: string;\n\n constructor(currencySettings: CurrencyConfig) {\n if (!currencySettings) {\n throw new Error('Currency settings missing');\n }\n\n const { decimalPlaces, symbolLocation, symbol, thousandsSeparator, decimalSeparator } =\n currencySettings;\n\n if (\n typeof symbolLocation !== 'string' ||\n typeof symbol !== 'string' ||\n typeof thousandsSeparator !== 'string' ||\n typeof decimalSeparator !== 'string' ||\n typeof decimalPlaces !== 'string'\n ) {\n throw new InvalidArgumentError('Invalid currency settings provided');\n }\n\n this._decimalPlaces = parseInt(decimalPlaces, 10);\n this._symbolLocation = symbolLocation;\n this._symbol = symbol;\n this._thousandsSeparator = thousandsSeparator;\n this._decimalSeparator = decimalSeparator;\n }\n\n format(amount?: number): string {\n if (typeof amount !== 'number') {\n throw new InvalidArgumentError('Invalid amount provided');\n }\n\n const formattedNumber = this._formatNumber(amount);\n\n const formattedCurrency = this._formatCurrency(formattedNumber);\n\n return amount < 0 ? `-${formattedCurrency}` : formattedCurrency;\n }\n\n private _formatNumber(amount: number): string {\n const positiveAmount = Math.abs(amount);\n const [integerAmount, decimalAmount = ''] = this._toFixed(\n positiveAmount,\n this._decimalPlaces,\n ).split('.');\n const parsedIntegerAmount = integerAmount.replace(\n /\\B(?=(\\d{3})+(?!\\d))/g,\n this._thousandsSeparator,\n );\n\n if (this._decimalPlaces < 1) {\n return parsedIntegerAmount;\n }\n\n return [parsedIntegerAmount, decimalAmount].join(this._decimalSeparator);\n }\n\n private _formatCurrency(formattedNumber: string): string {\n return this._symbolLocation.toLowerCase() === 'left'\n ? `${this._symbol}${formattedNumber}`\n : `${formattedNumber}${this._symbol}`;\n }\n\n private _toFixed(value: number, precision: number): string {\n return (+`${Math.round(+`${value}e${precision}`)}e${-precision}`).toFixed(precision);\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { StoreConfig } from '../config';\n\nimport CurrencyFormatter from './currency-formatter';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { Cart } from '../cart';\nimport { StoreConfig } from '../config';\n\nconst itemsRequireShipping = (cart?: Cart, config?: StoreConfig) => {\n if (!cart) {\n return false;\n }\n\n if (cart.lineItems.physicalItems.some((lineItem) => lineItem.isShippingRequired)) {\n return true;\n }\n\n if (config && cart.lineItems.customItems) {\n return cart.lineItems.customItems.length > 0;\n }\n\n return false;\n};\n\nexport default itemsRequireShipping;\n","import {\n BrowserInfo,\n BuyNowCartRequestBody,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { FundingType } from './google-pay-paypal-commerce/types';\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\nexport interface GooglePayGatewayBaseRequest {\n apiVersion: 2;\n apiVersionMinor: 0;\n}\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\ntype GooglePayGatewayBaseResponse = GooglePayGatewayBaseRequest;\n\ninterface GooglePayPaymentMethod {\n type: string;\n parameters: T;\n}\n\ntype GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS';\n\nexport enum GooglePayCardNetwork {\n AMEX = 'AMEX',\n DISCOVER = 'DISCOVER',\n INTERAC = 'INTERAC',\n JCB = 'JCB',\n MC = 'MASTERCARD',\n VISA = 'VISA',\n}\n\nexport interface GooglePayCardParameters {\n allowedAuthMethods: GooglePayAuthMethod[];\n allowedCardNetworks: GooglePayCardNetwork[];\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: 'MIN' | 'FULL';\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface GooglePayBaseCardPaymentMethod\n extends GooglePayPaymentMethod {\n type: 'CARD';\n parameters: GooglePayCardParameters;\n}\n\nexport interface GooglePayIsReadyToPayRequest extends GooglePayGatewayBaseRequest {\n allowedPaymentMethods: [GooglePayBaseCardPaymentMethod];\n}\n\ninterface GooglePayGatewayBaseParameters {\n gateway: string;\n}\n\nexport interface GooglePayRegularGatewayParameters extends GooglePayGatewayBaseParameters {\n gatewayMerchantId: string;\n}\n\nexport interface GooglePayStripeGatewayParameters extends GooglePayGatewayBaseParameters {\n 'stripe:version'?: string;\n 'stripe:publishableKey'?: string;\n}\n\nexport interface GooglePayBraintreeGatewayParameters extends GooglePayGatewayBaseParameters {\n 'braintree:apiVersion'?: string;\n 'braintree:authorizationFingerprint'?: string;\n 'braintree:merchantId'?: string;\n 'braintree:sdkVersion'?: string;\n}\n\nexport interface GooglePayPayPalCommerceGatewayParameters extends GooglePayGatewayBaseParameters {\n gatewayMerchantId?: string;\n}\n\nexport type GooglePayGatewayParameters =\n | GooglePayRegularGatewayParameters\n | GooglePayStripeGatewayParameters\n | GooglePayBraintreeGatewayParameters;\n\nexport interface GooglePayCardPaymentMethod extends GooglePayBaseCardPaymentMethod {\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY';\n parameters: GooglePayGatewayParameters;\n };\n}\n\nexport interface GooglePayTransactionInfo {\n /** [!] Required for EEA countries */\n countryCode?: string;\n currencyCode: string;\n totalPriceStatus: TotalPriceStatusType;\n totalPrice: string;\n}\n\nexport interface GooglePayMerchantInfo {\n merchantName: string;\n merchantId: string;\n authJwt: string;\n}\n\nexport enum CallbackIntentsType {\n OFFER = 'OFFER',\n PAYMENT_AUTHORIZATION = 'PAYMENT_AUTHORIZATION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n}\n\nexport interface GooglePayPaymentDataRequest extends GooglePayGatewayBaseRequest {\n allowedPaymentMethods: [GooglePayCardPaymentMethod];\n transactionInfo: GooglePayTransactionInfo;\n merchantInfo: GooglePayMerchantInfo;\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n shippingOptionRequired?: boolean;\n callbackIntents?: CallbackIntentsType[];\n}\n\nexport interface NewTransactionInfo {\n newTransactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport interface ShippingOptionParameters {\n defaultSelectedOptionId?: string;\n shippingOptions?: GoogleShippingOption[];\n}\n\nexport interface NewShippingOptionParameters {\n newShippingOptionParameters?: ShippingOptionParameters;\n}\n\nexport interface GoogleShippingOption {\n id: string;\n label?: string;\n}\n\nexport enum CallbackTriggerType {\n INITIALIZE = 'INITIALIZE',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n OFFER = 'OFFER',\n}\n\nexport interface IntermediatePaymentData {\n callbackTrigger: CallbackTriggerType;\n shippingAddress: GooglePayFullBillingAddress;\n shippingOptionData: GoogleShippingOption;\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): Promise<(NewTransactionInfo & NewShippingOptionParameters) | void>;\n };\n}\n\nexport type GooglePayRequiredPaymentData = Pick<\n GooglePayPaymentDataRequest,\n | 'emailRequired'\n | 'shippingAddressRequired'\n | 'shippingAddressParameters'\n | 'shippingOptionRequired'\n>;\n\ninterface GooglePayMinBillingAddress {\n name: string;\n postalCode: string;\n countryCode: string;\n phoneNumber?: string;\n}\n\nexport interface GooglePayFullBillingAddress extends GooglePayMinBillingAddress {\n address1: string;\n address2: string;\n address3: string;\n locality: string;\n administrativeArea: string;\n sortingCode: string;\n}\n\ninterface GooglePayCardInfo {\n cardNetwork: GooglePayCardNetwork;\n cardDetails: string;\n billingAddress?: GooglePayFullBillingAddress;\n}\n\ninterface GooglePayPaymentMethodData {\n description: string;\n tokenizationData: {\n type: 'PAYMENT_GATEWAY';\n token: string;\n };\n type: string;\n info: T;\n}\n\ninterface GooglePayCardData extends GooglePayPaymentMethodData {\n type: 'CARD';\n}\n\ninterface GooglePayPaymentDataResponse extends GooglePayGatewayBaseResponse {\n paymentMethodData: GooglePayPaymentMethodData;\n shippingAddress?: GooglePayFullBillingAddress;\n email?: string;\n}\n\nexport interface GooglePayCardDataResponse extends GooglePayPaymentDataResponse {\n paymentMethodData: GooglePayCardData;\n}\n\ninterface GooglePayIsReadyToPayResponse {\n result: boolean;\n}\n\nexport interface GooglePayButtonOptions {\n onClick: (event: MouseEvent) => void;\n allowedPaymentMethods: [GooglePayBaseCardPaymentMethod];\n buttonColor?: GooglePayButtonColor;\n buttonType?: GooglePayButtonType;\n}\n\nexport interface GooglePaymentsClient {\n isReadyToPay(request: GooglePayIsReadyToPayRequest): Promise;\n createButton(options: GooglePayButtonOptions): HTMLElement;\n loadPaymentData(request: GooglePayPaymentDataRequest): Promise;\n prefetchPaymentData(request: GooglePayPaymentDataRequest): void;\n}\n\ntype GooglePayEnvironment = 'TEST' | 'PRODUCTION';\n\nexport type GooglePaymentsClientConstructor = new (paymentOptions: {\n environment: GooglePayEnvironment;\n}) => GooglePaymentsClient;\n\nexport interface GooglePayHostWindow extends Window {\n google?: {\n payments: {\n api: {\n PaymentsClient: GooglePaymentsClientConstructor;\n };\n };\n };\n}\n\ninterface GooglePayBaseInitializationData {\n card_information?: { type: string; number: string; bin?: string; isNetworkTokenized?: boolean };\n gateway: string;\n gatewayMerchantId?: string;\n googleMerchantId: string;\n googleMerchantName: string;\n isThreeDSecureEnabled: boolean;\n nonce?: string;\n platformToken: string;\n storeCountry?: string;\n}\n\nexport interface GooglePayPayPalCommerceInitializationData extends GooglePayBaseInitializationData {\n merchantId?: string;\n clientId?: string;\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n orderId?: string;\n shouldRenderFields?: boolean;\n paymentButtonStyles?: Record;\n}\n\nexport interface GooglePayAuthorizeNetInitializationData extends GooglePayBaseInitializationData {\n paymentGatewayId: string;\n}\n\nexport interface GooglePayStripeInitializationData extends GooglePayBaseInitializationData {\n stripeConnectedAccount: string;\n stripePublishableKey: string;\n stripeVersion: string;\n}\n\nexport interface GooglePayCheckoutComInitializationData extends GooglePayBaseInitializationData {\n checkoutcomkey: string;\n}\n\nexport interface GooglePayAdyenV2InitializationData extends GooglePayBaseInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n prefillCardHolderName?: boolean;\n paymentMethodsResponse: object;\n}\n\nexport interface GooglePayAdyenV3InitializationData extends GooglePayBaseInitializationData {\n clientKey: string;\n environment?: string;\n prefillCardHolderName?: boolean;\n paymentMethodsResponse: object;\n}\n\nexport type GooglePayInitializationData =\n | GooglePayBaseInitializationData\n | GooglePayAdyenV2InitializationData\n | GooglePayAdyenV3InitializationData\n | GooglePayAuthorizeNetInitializationData\n | GooglePayStripeInitializationData\n | GooglePayCheckoutComInitializationData\n | GooglePayPayPalCommerceInitializationData;\n\nexport interface GooglePaySetExternalCheckoutData {\n nonce: string;\n card_information: { type: string; number: string; bin?: string; isNetworkTokenized?: boolean };\n cart_id?: string;\n}\n\nexport interface GooglePayAdditionalActionProcessable {\n processAdditionalAction(error: unknown, methodId?: string): Promise;\n}\n\nexport interface GooglePayErrorObject {\n errorCode?: number;\n statusCode: 'CANCELED' | 'DEVELOPER_ERROR';\n statusMessage?: string;\n}\n\nexport interface GooglePayTokenObject {\n protocolVersion: string;\n signature: string;\n signedMessage: string;\n}\n\nexport interface GooglePayStripeTokenObject {\n id: string;\n}\n\nexport interface GooglePayBraintreeTokenObject {\n androidPayCards: [\n {\n nonce: string;\n details: {\n bin: string;\n isNetworkTokenized?: boolean;\n };\n },\n ];\n}\n\nexport interface GooglePayCheckoutComTokenObject {\n token: string;\n}\n\nexport interface GooglePayThreeDSecureResult {\n three_ds_result: {\n acs_url: string;\n code: string;\n };\n}\n\nexport interface GooglePayBuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody;\n}\n\nexport interface ExtraPaymentData {\n deviceSessionId?: string;\n browser_info?: BrowserInfo;\n}\n\nexport type GooglePayButtonColor = 'default' | 'black' | 'white';\nexport type GooglePayButtonType =\n | 'book'\n | 'buy'\n | 'checkout'\n | 'donate'\n | 'order'\n | 'pay'\n | 'plain'\n | 'subscribe'\n | 'long'\n | 'short';\n\nexport interface TdOnlineMartThreeDSErrorBody {\n errors?: Array<{ code: string }>;\n three_ds_result?: {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n };\n}\n\nexport type TdOnlineMartAdditionalAction = RequestError;\n","import { GooglePayCardNetwork } from '../types';\n\nexport default function isGooglePayCardNetworkKey(\n card: string,\n): card is keyof typeof GooglePayCardNetwork {\n return card in GooglePayCardNetwork;\n}\n","import { round } from 'lodash';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n createCurrencyService,\n CurrencyService,\n guard,\n InvalidArgumentError,\n itemsRequireShipping,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n\n constructor(\n private _gatewayIdentifier: string,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n mapToShippingAddressRequestBody({\n shippingAddress,\n }: GooglePayCardDataResponse): AddressRequestBody | undefined {\n if (!shippingAddress) {\n return;\n }\n\n const { company = '', phone = '' } =\n this._paymentIntegrationService.getState().getShippingAddress() || {};\n\n return this._mapToAddressRequestBody(shippingAddress, company, phone);\n }\n\n mapToBillingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): BillingAddressRequestBody | undefined {\n const { billingAddress } = response.paymentMethodData.info;\n\n if (!billingAddress) {\n return;\n }\n\n const {\n company = '',\n phone = '',\n email,\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone),\n email: email || response.email,\n };\n }\n\n mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const {\n paymentMethodData: {\n tokenizationData: { token: nonce },\n info: { cardNetwork: type, cardDetails: number },\n },\n } = response;\n\n return Promise.resolve({\n nonce,\n card_information: { type, number },\n ...(this._isBuyNowFlow && {\n cart_id: this._paymentIntegrationService.getState().getCart()?.id,\n }),\n });\n }\n\n async getRequiredData(): Promise {\n const data: GooglePayRequiredPaymentData = { emailRequired: true };\n\n if (!this._isShippingAddressRequired()) {\n return data;\n }\n\n const state = await this._paymentIntegrationService.loadShippingCountries();\n const allowedCountryCodes = state.getShippingCountries()?.map((country) => country.code);\n\n return {\n ...data,\n shippingAddressRequired: true,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n ...(allowedCountryCodes && { allowedCountryCodes }),\n },\n shippingOptionRequired: true,\n };\n }\n\n getCallbackIntents(): CallbackIntentsType[] {\n if (this._isShippingAddressRequired()) {\n return [\n CallbackIntentsType.OFFER,\n CallbackIntentsType.SHIPPING_ADDRESS,\n CallbackIntentsType.SHIPPING_OPTION,\n ];\n }\n\n return [CallbackIntentsType.OFFER];\n }\n\n getCallbackTriggers(): { [key: string]: CallbackTriggerType[] } {\n const availableTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n CallbackTriggerType.SHIPPING_OPTION,\n ];\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n };\n }\n\n getNonce(methodId: string) {\n const nonce = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId)\n .initializationData?.nonce;\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return Promise.resolve(nonce);\n }\n\n extraPaymentData(): Promise {\n return Promise.resolve(undefined);\n }\n\n getMerchantInfo(): GooglePayMerchantInfo {\n const {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n } = this.getGooglePayInitializationData();\n\n return { merchantName, merchantId, authJwt };\n }\n\n getTransactionInfo(): GooglePayTransactionInfo {\n let currencyCode: string;\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n getPaymentGatewayParameters():\n | Promise\n | GooglePayGatewayParameters {\n const gatewayMerchantId = this.getGooglePayInitializationData().gatewayMerchantId;\n\n if (!gatewayMerchantId) {\n throw new InvalidArgumentError('Unable to proceed, gatewayMerchantId is missing.');\n }\n\n return {\n gateway: this._gatewayIdentifier,\n gatewayMerchantId,\n };\n }\n\n getCardParameters(): GooglePayCardParameters {\n const allowedCardNetworks = this.getPaymentMethod()\n .supportedCards.filter(isGooglePayCardNetworkKey)\n .map((key) => GooglePayCardNetwork[key]);\n\n return {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks,\n billingAddressRequired: true,\n billingAddressParameters: {\n format: 'FULL',\n phoneNumberRequired: true,\n },\n };\n }\n\n initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n this._getPaymentMethodFn = getPaymentMethod;\n this._isBuyNowFlow = Boolean(isBuyNowFlow);\n this._currencyCode = currencyCode;\n\n if (this._isBuyNowFlow) {\n this._getCurrencyCodeOrThrow();\n }\n\n return Promise.resolve();\n }\n\n async handleShippingAddressChange(\n shippingAddress?: GooglePayFullBillingAddress,\n ): Promise {\n if (shippingAddress) {\n shippingAddress.name = shippingAddress.name || '';\n shippingAddress.address1 = shippingAddress.address1 || '';\n }\n\n const mappedShippingAddress = this.mapToShippingAddressRequestBody({\n shippingAddress,\n } as GooglePayCardDataResponse);\n\n if (mappedShippingAddress) {\n await this._paymentIntegrationService.updateShippingAddress(mappedShippingAddress);\n }\n\n const state = this._paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n // Info: we can not return an empty data because shippingOptions should contain at least one element, it caused a developer exception\n return;\n }\n\n const consignment = consignments[0];\n const storeConfig = state.getStoreConfigOrThrow();\n\n if (!this._currencyService) {\n this._currencyService = createCurrencyService(storeConfig);\n }\n\n const availableShippingOptions = (consignment.availableShippingOptions || []).map(\n this._getGooglePayShippingOption.bind(this),\n );\n\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n\n if (availableShippingOptions.length) {\n const selectedShippingOptionId =\n consignment.selectedShippingOption?.id ||\n recommendedShippingOption?.id ||\n availableShippingOptions[0]?.id;\n\n if (!consignment.selectedShippingOption?.id && availableShippingOptions[0]) {\n await this.handleShippingOptionChange(\n recommendedShippingOption?.id || availableShippingOptions[0].id,\n );\n }\n\n return {\n defaultSelectedOptionId: selectedShippingOptionId,\n shippingOptions: availableShippingOptions,\n };\n }\n }\n\n async handleShippingOptionChange(optionId: string) {\n if (optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n getTotalPrice(): string {\n const { getCheckoutOrThrow, getCartOrThrow } = this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return totalPrice;\n }\n\n protected getGooglePayInitializationData(): GooglePayInitializationData {\n return guard(\n this.getPaymentMethod().initializationData,\n () => new InvalidArgumentError('Missing initialization data.'),\n );\n }\n\n protected getPaymentMethod(): PaymentMethod {\n return guard(\n this._getPaymentMethodFn,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n )();\n }\n\n protected getGatewayIdentifier(): string {\n return this._gatewayIdentifier;\n }\n\n protected setGatewayIdentifier(gateway?: string) {\n this._gatewayIdentifier = gateway || this.getGatewayIdentifier();\n }\n\n private _isShippingAddressRequired(): boolean {\n const { getCartOrThrow, getStoreConfig, getShippingAddress } =\n this._paymentIntegrationService.getState();\n\n return (\n getShippingAddress() === undefined &&\n itemsRequireShipping(getCartOrThrow(), getStoreConfig())\n );\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n ): AddressRequestBody {\n const {\n name,\n address1,\n address2,\n address3,\n locality: city,\n administrativeArea: stateOrProvinceCode,\n countryCode,\n postalCode,\n phoneNumber,\n } = address;\n const [firstName, lastName] = this._getFirstAndLastName(name);\n\n return {\n firstName,\n lastName,\n company,\n address1,\n address2: `${address2} ${address3}`.trim(),\n city: city || stateOrProvinceCode,\n stateOrProvince: stateOrProvinceCode,\n stateOrProvinceCode,\n countryCode,\n postalCode,\n phone: phoneNumber || phone,\n customFields: [],\n };\n }\n\n private _getFirstAndLastName(fullName: string): [string, string] {\n const nameParts = fullName.split(' ');\n\n if (nameParts.length === 1) {\n return [fullName, ''];\n }\n\n const firstName = nameParts.slice(0, -1).join(' ');\n const lastName = nameParts[nameParts.length - 1];\n\n return [firstName, lastName];\n }\n\n private _getCurrencyCodeOrThrow(): string {\n return guard(\n this._currencyCode,\n () =>\n new InvalidArgumentError(\n 'Unable to initialize payment because \"options.currencyCode\" argument is not provided.',\n ),\n );\n }\n\n private _getGooglePayShippingOption({ id, cost, description }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: description,\n description: formattedCost || cost,\n };\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * param config - The config object containing the currency configuration\n * returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import { GooglePayErrorObject } from '../types';\n\nexport default function isGooglePayErrorObject(error: unknown): error is GooglePayErrorObject {\n return typeof error === 'object' && error !== null && 'statusCode' in error;\n}\n","/**\n * A set of options that are required to initialize the GooglePay payment method\n *\n * If the customer chooses to pay with GooglePay, they will be asked to\n * enter their payment details via a modal. You can hook into events emitted by\n * the modal by providing the callbacks listed below.\n *\n * ```html\n * \n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * // Using GooglePay provided by Braintree as an example\n * methodId: 'googlepaybraintree',\n * googlepaybraintree: {\n * walletButton: 'wallet-button'\n * },\n * });\n * ```\n *\n * Additional event callbacks can be registered.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'googlepaybraintree',\n * googlepaybraintree: {\n * walletButton: 'wallet-button',\n * onError(error) {\n * console.log(error);\n * },\n * onPaymentSelect() {\n * console.log('Selected');\n * },\n * },\n * });\n * ```\n */\nexport default interface GooglePayPaymentInitializeOptions {\n /**\n * This walletButton is used to set an event listener, provide an element ID if you want\n * users to be able to launch the GooglePay wallet modal by clicking on a button.\n * It should be an HTML element.\n */\n walletButton?: string;\n\n /**\n * A callback that gets called when GooglePay fails to initialize or\n * selects a payment option.\n *\n * @param error - The error object describing the failure.\n */\n onError?(error: Error): void;\n\n /**\n * A callback that gets called when the customer selects a payment option.\n */\n onPaymentSelect?(): void;\n}\n\n/**\n * The recognized keys to pass the initialization options for Google Pay.\n */\nexport enum GooglePayKey {\n ADYEN_V2 = 'googlepayadyenv2',\n ADYEN_V3 = 'googlepayadyenv3',\n AUTHORIZE_NET = 'googlepayauthorizenet',\n BNZ = 'googlepaybnz',\n BRAINTREE = 'googlepaybraintree',\n PAYPAL_COMMERCE = 'googlepaypaypalcommerce',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n WORLDPAY_ACCESS = 'googlepayworldpayaccess',\n TD_ONLINE_MART = 'googlepaytdonlinemart',\n}\n\n/**\n * The options that are required to initialize the GooglePay payment method.\n * They can be omitted unless you need to support GooglePay.\n */\nexport type WithGooglePayPaymentInitializeOptions = {\n [k in GooglePayKey]?: GooglePayPaymentInitializeOptions;\n};\n","import { GooglePayKey } from '../google-pay-payment-initialize-options';\n\nexport default function isGooglePayKey(key: string): key is GooglePayKey {\n return Object.values(GooglePayKey).includes(key);\n}\n","import {\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n guard,\n InvalidArgumentError,\n NotImplementedError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCustomerInitializeOptions, {\n WithGooglePayCustomerInitializeOptions,\n} from './google-pay-customer-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayCustomerStrategy implements CustomerStrategy {\n private _paymentButton?: HTMLElement;\n private _methodId?: keyof WithGooglePayCustomerInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options?: CustomerInitializeOptions & WithGooglePayCustomerInitializeOptions,\n ): Promise {\n if (!options?.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n const googlePayOptions = options[this._getMethodId()];\n\n if (!googlePayOptions) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n let state = this._paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodId());\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodId());\n }\n\n try {\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(paymentMethod.initializationData?.storeCountry),\n );\n } catch {\n return;\n }\n\n this._addPaymentButton(googlePayOptions);\n }\n\n signIn(): Promise {\n return Promise.reject(\n new NotImplementedError(\n 'In order to sign in via Google Pay, the shopper must click on \"Google Pay\" button.',\n ),\n );\n }\n\n async signOut(): Promise {\n const providerId = this._paymentIntegrationService.getState().getPaymentId()?.providerId;\n\n if (providerId) {\n await this._googlePayPaymentProcessor.signOut(providerId);\n }\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n this._paymentButton?.remove();\n this._paymentButton = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n private _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n }: IntermediatePaymentData): Promise => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n } = this._googlePayPaymentProcessor.getCallbackTriggers();\n\n if (!availableTriggers.includes(callbackTrigger)) {\n return;\n }\n\n const availableShippingOptions = addressChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleShippingAddressChange(\n shippingAddress,\n )\n : undefined;\n\n if (shippingOptionsChangeTriggers.includes(callbackTrigger)) {\n await this._googlePayPaymentProcessor.handleShippingOptionChange(\n shippingOptionData.id,\n );\n }\n\n await this._paymentIntegrationService.loadCheckout();\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n },\n },\n };\n }\n\n private _addPaymentButton({\n container,\n buttonColor,\n buttonType,\n onClick,\n onError,\n }: GooglePayCustomerInitializeOptions): void {\n this._paymentButton =\n this._paymentButton ??\n this._googlePayPaymentProcessor.addPaymentButton(container, {\n buttonColor: buttonColor ?? 'default',\n buttonType: buttonType ?? 'plain',\n onClick: this._handleClick(onError, onClick),\n });\n }\n\n private _handleClick(\n onError: GooglePayCustomerInitializeOptions['onError'],\n onClick: GooglePayCustomerInitializeOptions['onClick'],\n ): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n if (onClick && typeof onClick === 'function') {\n onClick();\n }\n\n // TODO: Dispatch Widget Actions\n try {\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n };\n }\n\n private async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n const shippingAddress =\n this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(response);\n const siteLink =\n window.location.pathname === '/embedded-checkout'\n ? this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink\n : undefined;\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress) {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutForm(\n this._getMethodId(),\n response,\n siteLink,\n );\n }\n\n private _getMethodId(): keyof WithGooglePayCustomerInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethod,\n PaymentMethodFailedError,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from './gateways/google-pay-gateway';\nimport GooglePayScriptLoader from './google-pay-script-loader';\nimport isGooglePayAdditionalActionProcessable from './guards/is-google-pay-additional-action-processable';\nimport {\n GooglePayBaseCardPaymentMethod,\n GooglePayButtonOptions,\n GooglePayCardDataResponse,\n GooglePayCardPaymentMethod,\n GooglePayFullBillingAddress,\n GooglePayGatewayBaseRequest,\n GooglePayInitializationData,\n GooglePayIsReadyToPayRequest,\n GooglePaymentsClient,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\n ShippingOptionParameters,\n} from './types';\n\nexport default class GooglePayPaymentProcessor {\n private _paymentsClient?: GooglePaymentsClient;\n private _baseRequest: GooglePayGatewayBaseRequest = { apiVersion: 2, apiVersionMinor: 0 };\n private _baseCardPaymentMethod?: GooglePayBaseCardPaymentMethod;\n private _cardPaymentMethod?: GooglePayCardPaymentMethod;\n private _paymentDataRequest?: GooglePayPaymentDataRequest;\n private _isReadyToPayRequest?: GooglePayIsReadyToPayRequest;\n\n constructor(\n private _scriptLoader: GooglePayScriptLoader,\n private _gateway: GooglePayGateway,\n private _requestSender: RequestSender,\n private _formPoster: FormPoster,\n ) {}\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n googlePayPaymentOptions?: GooglePayPaymentOptions,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n this._paymentsClient = await this._scriptLoader.getGooglePaymentsClient(\n getPaymentMethod().config.testMode,\n googlePayPaymentOptions,\n );\n\n await this._gateway.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n this._buildButtonPayloads();\n }\n\n async initializeWidget() {\n await this._buildWidgetPayloads();\n\n await this._determineReadinessToPay();\n\n this._prefetchGooglePaymentData();\n }\n\n getNonce(methodId: string) {\n return this._gateway.getNonce(methodId);\n }\n\n async extraPaymentData() {\n return this._gateway.extraPaymentData();\n }\n\n addPaymentButton(\n containerId: string,\n options: Omit,\n ): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Google Pay button to an invalid HTML container element.',\n );\n }\n\n const paymentButton = this._getPaymentsClient().createButton({\n ...options,\n allowedPaymentMethods: [this._getBaseCardPaymentMethod()],\n });\n\n return container.appendChild(paymentButton);\n }\n\n async showPaymentSheet(): Promise {\n const paymentDataRequest = this._getPaymentDataRequest();\n\n return this._getPaymentsClient().loadPaymentData(paymentDataRequest);\n }\n\n async setExternalCheckoutXhr(\n provider: string,\n response: GooglePayCardDataResponse,\n ): Promise {\n return this._setExternalCheckout(provider, response);\n }\n\n async setExternalCheckoutForm(\n provider: string,\n response: GooglePayCardDataResponse,\n siteLink?: string,\n ): Promise {\n return this._setExternalCheckout(provider, response, true, siteLink);\n }\n\n mapToBillingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): BillingAddressRequestBody | undefined {\n return this._gateway.mapToBillingAddressRequestBody(response);\n }\n\n mapToShippingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): AddressRequestBody | undefined {\n return this._gateway.mapToShippingAddressRequestBody(response);\n }\n\n processAdditionalAction(error: unknown, methodId?: string): Promise {\n return isGooglePayAdditionalActionProcessable(this._gateway)\n ? this._gateway.processAdditionalAction(error, methodId)\n : Promise.reject(error);\n }\n\n async signOut(providerId: string): Promise {\n await this._requestSender.get(`/remote-checkout/${providerId}/signout`);\n }\n\n getCallbackTriggers() {\n return this._gateway.getCallbackTriggers();\n }\n\n async handleShippingAddressChange(\n shippingAddress: GooglePayFullBillingAddress,\n ): Promise {\n return this._gateway.handleShippingAddressChange(shippingAddress);\n }\n\n async handleShippingOptionChange(optionId: string): Promise {\n await this._gateway.handleShippingOptionChange(optionId);\n }\n\n getTotalPrice(): string {\n return this._gateway.getTotalPrice();\n }\n\n async _setExternalCheckout(\n provider: string,\n response: GooglePayCardDataResponse,\n useFormPoster = false,\n siteLink?: string,\n ): Promise {\n const url = '/checkout.php';\n const body = {\n action: 'set_external_checkout',\n provider,\n ...(await this._gateway.mapToExternalCheckoutData(response)),\n };\n\n if (useFormPoster) {\n return new Promise((resolve) => {\n this._formPoster.postForm(\n siteLink ? `${siteLink}/checkout` : url,\n {\n ...body,\n card_information: JSON.stringify(body.card_information),\n },\n resolve,\n );\n });\n }\n\n await this._requestSender.post(url, {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body,\n });\n }\n\n private _prefetchGooglePaymentData(): void {\n const paymentDataRequest = this._getPaymentDataRequest();\n\n paymentDataRequest.transactionInfo = this._gateway.getTransactionInfo();\n\n this._getPaymentsClient().prefetchPaymentData(paymentDataRequest);\n }\n\n private async _determineReadinessToPay(): Promise {\n try {\n const { result } = await this._getPaymentsClient().isReadyToPay(\n this._getIsReadyToPayRequest(),\n );\n\n if (result === false) {\n throw new PaymentMethodFailedError(\n 'Google Pay is not supported by the current device and browser, please try another payment method.',\n );\n }\n } catch (error) {\n if (error instanceof PaymentMethodFailedError) {\n throw error;\n }\n\n throw new PaymentMethodFailedError();\n }\n }\n\n private _buildButtonPayloads() {\n this._baseCardPaymentMethod = {\n type: 'CARD',\n parameters: this._gateway.getCardParameters(),\n };\n }\n\n private async _buildWidgetPayloads(): Promise {\n const baseCardPaymentMethod = this._getBaseCardPaymentMethod();\n\n this._cardPaymentMethod = {\n ...baseCardPaymentMethod,\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: await this._gateway.getPaymentGatewayParameters(),\n },\n };\n this._paymentDataRequest = {\n ...this._baseRequest,\n allowedPaymentMethods: [this._cardPaymentMethod],\n transactionInfo: this._gateway.getTransactionInfo(),\n merchantInfo: this._gateway.getMerchantInfo(),\n ...(await this._gateway.getRequiredData()),\n callbackIntents: this._gateway.getCallbackIntents(),\n };\n this._isReadyToPayRequest = {\n ...this._baseRequest,\n allowedPaymentMethods: [baseCardPaymentMethod],\n };\n }\n\n private _getBaseCardPaymentMethod(): GooglePayBaseCardPaymentMethod {\n return this._getOrThrow(this._baseCardPaymentMethod);\n }\n\n private _getPaymentDataRequest(): GooglePayPaymentDataRequest {\n return this._getOrThrow(this._paymentDataRequest);\n }\n\n private _getIsReadyToPayRequest(): GooglePayIsReadyToPayRequest {\n return this._getOrThrow(this._isReadyToPayRequest);\n }\n\n private _getPaymentsClient(): GooglePaymentsClient {\n return this._getOrThrow(this._paymentsClient);\n }\n\n private _getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","import GooglePayGateway from '../gateways/google-pay-gateway';\nimport { GooglePayAdditionalActionProcessable } from '../types';\n\nexport default function isGooglePayAdditionalActionProcessable(\n gateway: GooglePayGateway,\n): gateway is GooglePayGateway & GooglePayAdditionalActionProcessable {\n return 'processAdditionalAction' in gateway;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayHostWindow, GooglePaymentsClient, GooglePayPaymentOptions } from './types';\n\nexport const GOOGLE_PAY_LIBRARY = 'https://pay.google.com/gp/p/js/pay.js';\n\nexport default class GooglePayScriptLoader {\n private _paymentsClient?: GooglePaymentsClient;\n private _window: GooglePayHostWindow = window;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async getGooglePaymentsClient(\n testMode = false,\n options?: GooglePayPaymentOptions,\n ): Promise {\n await this._scriptLoader.loadScript(GOOGLE_PAY_LIBRARY);\n\n if (!this._window.google) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n if (this._paymentsClient === undefined) {\n this._paymentsClient = new this._window.google.payments.api.PaymentsClient({\n environment: testMode ? 'TEST' : 'PRODUCTION',\n ...(options ?? {}),\n });\n }\n\n return this._paymentsClient;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport GooglePayScriptLoader from '../google-pay-script-loader';\n\nexport default function createGooglePayScriptLoader() {\n return new GooglePayScriptLoader(getScriptLoader());\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV2CustomerStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV3CustomerStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertsIsGooglePayAuthorizeNetInitializationData from '../guards/is-google-pay-authorizenet-initialization-data';\nimport {\n GooglePayCardDataResponse,\n GooglePayGatewayParameters,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAuthorizeNetGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('authorizenet', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayAuthorizeNetInitializationData(data);\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId: data.paymentGatewayId,\n };\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayAuthorizeNetInitializationData, GooglePayInitializationData } from '../types';\n\nfunction isGooglePayAuthorizeNetInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayAuthorizeNetInitializationData {\n return 'paymentGatewayId' in data;\n}\n\nexport default function assertsIsGooglePayAuthorizeNetInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayAuthorizeNetInitializationData {\n if (!isGooglePayAuthorizeNetInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeDotNetCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAuthorizeDotNetCustomerStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import RequestError from './request-error';\n\n// Have to use `as` https://stackoverflow.com/questions/73987044/typeguarding-an-unknown-nested-object should be fixed in 4.8+\nconst isRequestError = (error: unknown): error is RequestError => {\n return typeof error === 'object' && error !== null && 'body' in error;\n};\n\nexport default isRequestError;\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCheckoutComInitializationData, GooglePayInitializationData } from '../types';\n\nfunction isGooglePayCheckoutComInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayCheckoutComInitializationData {\n return 'checkoutcomkey' in data;\n}\n\nexport default function assertIsGooglePayCheckoutComInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayCheckoutComInitializationData {\n if (!isGooglePayCheckoutComInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n InvalidArgumentError,\n isRequestError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertIsGooglePayCheckoutComInitializationData from '../guards/is-google-pay-checkoutcom-initialization-data';\nimport { isGooglePayThreeDSecureResult } from '../guards/is-google-pay-threedsecure-result';\nimport assertIsGooglePayTokenObject from '../guards/is-google-pay-token-object';\nimport {\n GooglePayAdditionalActionProcessable,\n GooglePayCardDataResponse,\n GooglePayCheckoutComTokenObject,\n GooglePayGatewayParameters,\n GooglePaySetExternalCheckoutData,\n GooglePayTokenObject,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayCheckoutComGateway\n extends GooglePayGateway\n implements GooglePayAdditionalActionProcessable\n{\n constructor(service: PaymentIntegrationService, private _requestSender: RequestSender) {\n super('checkoutltd', service);\n }\n\n processAdditionalAction(error: unknown): Promise {\n return new Promise((_resolve, reject) => {\n if (\n isRequestError(error) &&\n isGooglePayThreeDSecureResult(error.body) &&\n error.body.three_ds_result.code === 'three_d_secure_required'\n ) {\n return window.location.assign(error.body.three_ds_result.acs_url);\n }\n\n reject(error);\n });\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayTokenObject(token);\n\n data.nonce = await this._tokenize(token);\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertIsGooglePayCheckoutComInitializationData(data);\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId: data.checkoutcomkey,\n };\n }\n\n private async _tokenize(token_data: GooglePayTokenObject): Promise {\n const url = this.getPaymentMethod().config.testMode\n ? 'https://api.sandbox.checkout.com/tokens'\n : 'https://api.checkout.com/tokens';\n const data = this.getGooglePayInitializationData();\n\n assertIsGooglePayCheckoutComInitializationData(data);\n\n const { body } = await this._requestSender.post(url, {\n credentials: false,\n body: {\n type: 'googlepay',\n token_data,\n },\n headers: {\n Authorization: data.checkoutcomkey,\n 'Content-Type': ContentType.Json,\n 'X-XSRF-TOKEN': null,\n },\n });\n\n return body.token;\n }\n}\n","import { RequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayThreeDSecureResult } from '../types';\n\nexport function isGooglePayThreeDSecureResult(\n body: RequestError['body'],\n): body is GooglePayThreeDSecureResult {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n\n const threeDSBody = body as Partial;\n\n return (\n typeof threeDSBody.three_ds_result?.acs_url === 'string' &&\n typeof threeDSBody.three_ds_result.code === 'string'\n );\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayTokenObject } from '../types';\n\nfunction isGooglePayTokenObject(token: unknown): token is GooglePayTokenObject {\n return (\n typeof token === 'object' &&\n token !== null &&\n 'protocolVersion' in token &&\n 'signature' in token &&\n 'signedMessage' in token\n );\n}\n\nexport default function assertIsGooglePayTokenObject(\n token: unknown,\n): asserts token is GooglePayTokenObject {\n if (!isGooglePayTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComCustomerStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayCybersourceGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('cybersource', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourceCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCybersourceCustomerStrategy, [\n { id: 'googlepaycybersourcev2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBnzCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBnzCustomerStrategy, [{ id: 'googlepaybnz' }]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayOrbitalGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('chase', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayOrbitalCustomerStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import InvalidArgumentError from './invalid-argument-error';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData, GooglePayStripeInitializationData } from '../types';\n\nfunction isGooglePayStripeInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayStripeInitializationData {\n return (\n 'stripeConnectedAccount' in data &&\n 'stripePublishableKey' in data &&\n 'stripeVersion' in data\n );\n}\n\nexport default function assertsIsGooglePayStripeInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayStripeInitializationData {\n if (!isGooglePayStripeInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { includes, some } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isRequestError,\n PaymentArgumentInvalidError,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../gateways/google-pay-gateway';\nimport assertsIsGooglePayStripeInitializationData from '../guards/is-google-pay-stripe-initialization-data';\nimport isGooglePayStripeRequestError from '../guards/is-google-pay-stripe-request-error';\nimport assertIsGooglePayStripeTokenObject from '../guards/is-google-pay-stripe-token-object';\nimport {\n GooglePayCardDataResponse,\n GooglePaySetExternalCheckoutData,\n GooglePayStripeGatewayParameters,\n} from '../types';\n\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\nimport { StripeError, StripeUPEClient } from './types';\n\nexport default class GooglePayStripeGateway extends GooglePayGateway {\n private stripeUPEClient?: StripeUPEClient;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {\n super('stripe', paymentIntegrationService);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayStripeTokenObject(token);\n\n data.nonce = token.id;\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayStripeGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(data);\n\n const { stripeVersion, stripePublishableKey, stripeConnectedAccount } = data;\n\n return {\n gateway: this.getGatewayIdentifier(),\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n };\n }\n\n async processAdditionalAction(\n error: unknown,\n methodId?: string,\n ): Promise {\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!isRequestError(error) || !isGooglePayStripeRequestError(error.body)) {\n throw error;\n }\n\n const state = this.paymentIntegrationService.getState();\n const isStripeGooglePay3dsExperimentIsOn =\n state.getStoreConfig()?.checkoutSettings.features[\n 'STRIPE-476.enable_stripe_googlepay_3ds'\n ];\n const shouldTrigger3DS =\n some(error.body.errors, { code: 'three_d_secure_required' }) &&\n isStripeGooglePay3dsExperimentIsOn;\n\n if (shouldTrigger3DS) {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(data);\n\n const { stripePublishableKey, stripeConnectedAccount } = data;\n\n this.stripeUPEClient = await this.loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this.stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (_) {\n try {\n result = await this.stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (__) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n return this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: { nonce: result?.paymentIntent?.id || clientSecret },\n });\n }\n\n throw error;\n }\n\n private async loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayStripeTokenObject } from '../types';\n\nfunction isGooglePayStripeTokenObject(token: unknown): token is GooglePayStripeTokenObject {\n return typeof token === 'object' && token !== null && 'id' in token;\n}\n\nexport default function assertIsGooglePayStripeTokenObject(\n token: unknown,\n): asserts token is GooglePayStripeTokenObject {\n if (!isGooglePayStripeTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","interface AdditionalActionError {\n three_ds_result: { token: string };\n errors: Array<{ code: string }>;\n}\n\nconst isGooglePayStripeRequestError = (body: unknown): body is AdditionalActionError => {\n return (\n typeof body === 'object' && body !== null && 'three_ds_result' in body && 'errors' in body\n );\n};\n\nexport default isGooglePayStripeRequestError;\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripeHostWindow, StripeUPEClient } from './types';\n\nexport default class StripeUPEScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this.stripeWindow.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n private async load() {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript('https://js.stripe.com/v3/');\n }\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.stripeWindow.Stripe;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeUpeCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeUpeCustomerStrategy, [\n { id: 'googlepaystripeupe' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayWorldpayAccessGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('worldpay', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayWorldpayAccessCustomerStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","export default class CancellablePromise {\n promise: Promise;\n cancel!: (reason?: any) => void;\n\n constructor(promise: Promise) {\n const cancellable = new Promise((_, reject) => {\n this.cancel = reject;\n });\n\n this.promise = Promise.race([promise, cancellable]);\n }\n}\n","import {\n BraintreeGooglePayment,\n BraintreeGooglePayThreeDSecure,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CancellablePromise,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertIsGooglePayBraintreeTokenObject from '../guards/is-google-pay-braintree-token-object';\nimport {\n GooglePayCardDataResponse,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayBraintreeGateway extends GooglePayGateway {\n private _braintreeGooglePayment?: BraintreeGooglePayment;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _braintreeSdk: BraintreeSdk) {\n super('braintree', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken || !paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeSdk.initialize(paymentMethod.clientToken);\n this._braintreeGooglePayment = await this._braintreeSdk.getBraintreeGooglePayment();\n\n return Promise.resolve();\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n\n const { clientToken, initializationData } = super.getPaymentMethod();\n\n if (!clientToken || !initializationData || !initializationData.card_information?.bin) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n isThreeDSecureEnabled,\n card_information: { bin, isNetworkTokenized },\n } = initializationData;\n\n if (isThreeDSecureEnabled && !isNetworkTokenized) {\n const threeDSecure = await this._braintreeSdk.getBraintreeThreeDS();\n\n const { orderAmount } = this._service.getState().getOrderOrThrow();\n\n const verification = await this._braintreePresent3DSChallenge(\n threeDSecure,\n orderAmount,\n nonce,\n bin,\n );\n\n return verification.nonce;\n }\n\n return nonce;\n }\n\n async extraPaymentData() {\n return {\n deviceSessionId: await this._getBraintreeDeviceData(),\n };\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayBraintreeTokenObject(token);\n\n data.nonce = token.androidPayCards[0].nonce;\n data.card_information.bin = token.androidPayCards[0].details.bin;\n data.card_information.isNetworkTokenized =\n token.androidPayCards[0].details.isNetworkTokenized;\n\n return data;\n }\n\n getCardParameters() {\n return super.getCardParameters();\n }\n\n async getPaymentGatewayParameters(): Promise {\n const braintreeGooglePayment = this.getBraintreeGooglePayment();\n\n const request = braintreeGooglePayment.createPaymentDataRequest({\n merchantInfo: super.getMerchantInfo(),\n transactionInfo: super.getTransactionInfo(),\n cardRequirements: {\n billingAddressRequired: true,\n billingAddressFormat: 'FULL',\n },\n ...(await super.getRequiredData()),\n });\n\n return request.paymentMethodTokenizationParameters.parameters;\n }\n\n private getBraintreeGooglePayment(): BraintreeGooglePayment {\n if (!this._braintreeGooglePayment) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._braintreeGooglePayment;\n }\n\n private async _getBraintreeDeviceData(): Promise {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n }\n\n private _braintreePresent3DSChallenge(\n threeDSecure: BraintreeGooglePayThreeDSecure,\n amount: number,\n nonce: string,\n bin: string,\n ) {\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n amount,\n bin,\n nonce,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayBraintreeTokenObject } from '../types';\n\nfunction isGooglePayBraintreeTokenObject(token: unknown): token is GooglePayBraintreeTokenObject {\n return typeof token === 'object' && token !== null && 'androidPayCards' in token;\n}\n\nexport default function assertIsGooglePayBraintreeTokenObject(\n token: unknown,\n): asserts token is GooglePayBraintreeTokenObject {\n if (!isGooglePayBraintreeTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreePaymentStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreePaymentStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","import {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../gateways/google-pay-gateway';\nimport assertsIsGooglePayPayPalCommercePaymentMethod from '../guards/is-google-pay-paypal-commerce-payment-method';\nimport {\n GooglePayCardDataResponse,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\nimport { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(\n service: PaymentIntegrationService,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {\n super('paypalsb', service);\n\n this.service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n const currency = this.service.getState().getStoreConfig()?.currency.code ?? currencyCode;\n\n if (!currency) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await super.initialize(getPaymentMethod, isBuyNowFlow, currency);\n\n const paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n assertsIsGooglePayPayPalCommercePaymentMethod(paymentMethod);\n\n await this.paypalCommerceScriptLoader.getPayPalSDK(paymentMethod, currency);\n\n this.googlepayConfig = await this.paypalCommerceScriptLoader.getGooglePayConfigOrThrow();\n\n const { allowedPaymentMethods } = this.googlepayConfig;\n\n this.setGatewayIdentifier(\n allowedPaymentMethods[0]?.tokenizationSpecification?.parameters?.gateway,\n );\n }\n\n getPaymentGatewayParameters(): GooglePayPayPalCommerceGatewayParameters {\n if (this.googlepayConfig) {\n const { allowedPaymentMethods } = this.googlepayConfig;\n const { gatewayMerchantId } =\n allowedPaymentMethods[0].tokenizationSpecification.parameters;\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId,\n };\n }\n\n return {\n gateway: this.getGatewayIdentifier(),\n };\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nfunction isGooglePayPaypalCommercePaymentMethod(\n data: PaymentMethod,\n): data is PaymentMethod {\n if (data.initializationData) {\n return (\n 'attributionId' in data.initializationData &&\n 'isVenmoEnabled' in data.initializationData &&\n 'isGooglePayEnabled' in data.initializationData &&\n 'isPayPalCreditAvailable' in data.initializationData\n );\n }\n\n return false;\n}\n\nexport default function assertsIsGooglePayPayPalCommercePaymentMethod(\n data: PaymentMethod,\n): asserts data is PaymentMethod {\n if (!isGooglePayPaypalCommercePaymentMethod(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport {\n ComponentsScriptType,\n FundingType,\n GooglePayConfig,\n PayPalCommerceHostWindow,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './types';\n\nexport default class GooglePayPayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n private googlepayConfig?: GooglePayConfig;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.loadPayPalSDK(paypalSdkScriptConfig, forceLoad);\n }\n\n async getGooglePayConfigOrThrow() {\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n if (!this.googlepayConfig) {\n this.googlepayConfig = await this.window.paypal.Googlepay().config();\n }\n\n return this.googlepayConfig;\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const options = this.transformConfig(\n paypalSdkScriptConfig.options,\n );\n const attributes = this.transformConfig(\n paypalSdkScriptConfig.attributes,\n );\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(options).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes });\n }\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n isGooglePayEnabled,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: [\n 'buttons',\n 'hosted-fields',\n 'messages',\n 'payment-fields',\n 'legal',\n ...googlePayComponent,\n ...cardFieldsComponent,\n ],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(\n paymentIntegrationService,\n new PayPalCommerceScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n const { navigator } = window;\n\n let language: string;\n\n if (navigator.language) {\n language = navigator.language;\n } else {\n language = (navigator as any).userLanguage;\n }\n\n return {\n color_depth: window.screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language,\n screen_height: window.screen.height,\n screen_width: window.screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n getBrowserInfo,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isTdOnlineMartAdditionalAction } from '../guards/is-google-pay-td-online-mart-additional-action';\nimport { ExtraPaymentData, TdOnlineMartThreeDSErrorBody } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayTdOnlineMartGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService, private formPoster: FormPoster) {\n super('worldlinena', service);\n }\n\n async extraPaymentData(): Promise {\n return Promise.resolve({ browser_info: getBrowserInfo() });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isTdOnlineMartAdditionalAction(error)) {\n throw error;\n }\n\n const { three_ds_result: threeDSResult }: TdOnlineMartThreeDSErrorBody = error.body;\n const {\n acs_url: formUrl,\n payer_auth_request: threeDSSessionData,\n merchant_data: creq,\n } = threeDSResult || {};\n\n if (!formUrl || !threeDSSessionData || !creq) {\n throw new PaymentArgumentInvalidError(['formUrl', 'threeDSSessionData', 'creq']);\n }\n\n return new Promise((resolve) => {\n this.formPoster.postForm(\n formUrl,\n {\n threeDSSessionData,\n creq,\n },\n resolve,\n '_top',\n );\n });\n }\n}\n","import { isArray, isObject, some } from 'lodash';\n\nimport { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TdOnlineMartAdditionalAction, TdOnlineMartThreeDSErrorBody } from '../types';\n\nfunction isTdOnlineMartThreeDSErrorBody(\n errorBody: unknown,\n): errorBody is TdOnlineMartThreeDSErrorBody {\n return (\n isObject(errorBody) &&\n typeof errorBody === 'object' &&\n 'errors' in errorBody &&\n 'three_ds_result' in errorBody &&\n isArray((errorBody as TdOnlineMartThreeDSErrorBody).errors) &&\n some((errorBody as TdOnlineMartThreeDSErrorBody).errors, {\n code: 'three_d_secure_required',\n })\n );\n}\n\nexport function isTdOnlineMartAdditionalAction(\n error: unknown,\n): error is TdOnlineMartAdditionalAction {\n return isRequestError(error) && isTdOnlineMartThreeDSErrorBody(error.body);\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) =>\n new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartCustomerStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","export enum CartSource {\n BuyNow = 'BUY_NOW',\n}\n","import {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\nexport interface PayPalCommerceSDKFunding {\n CARD: string;\n PAYPAL: string;\n CREDIT: string;\n PAYLATER: string;\n OXXO: string;\n SEPA: string;\n VENMO: string;\n}\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\n\nexport interface PayPalCommerceCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCommerceCardFieldsState): void;\n onFocus(data: PayPalCommerceCardFieldsState): void;\n onBlur(data: PayPalCommerceCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCommerceCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCommerceCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalCommerceHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCommerceCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface PayPalCommerceCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\ninterface PayPalCommerceCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCommerceCardFieldsCard = PayPalCommerceHostedFieldsCard;\n\nexport interface PayPalCommerceCardFieldsState {\n cards: PayPalCommerceCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCommerceCardFieldsFieldData;\n cardNumberField: PayPalCommerceCardFieldsFieldData;\n cardNameField?: PayPalCommerceCardFieldsFieldData;\n cardExpiryField: PayPalCommerceCardFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface PayPalCommerceFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCommerceCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n ExpiryField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n NameField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n NumberField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n submit(config?: PayPalCommerceCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCommerceCardFieldsSubmitConfig {\n billingAddress: {\n company?: string;\n addressLine1: string;\n addressLine2?: string;\n adminArea1: string; // State\n adminArea2: string; // City\n postalCode: string;\n countryCode?: string;\n };\n}\n\nexport interface PayPalSDK {\n CardFields: (data: PayPalCommerceCardFieldsConfig) => Promise;\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (arg0: {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n }) => Promise<{ status: string }>;\n initiatePayerAction: () => void;\n };\n FUNDING: PayPalCommerceSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(data: PayPalCommerceHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n Messages(options: PayPalCommerceMessagesOptions): PayPalCommerceMessages;\n}\n\nexport interface ConfirmOrderData {\n tokenizationData: {\n type: string;\n token: string;\n };\n info: {\n cardNetwork: string;\n cardDetails: string;\n };\n type: string;\n}\n\nexport interface GooglePayConfig {\n allowedPaymentMethods: AllowedPaymentMethods[];\n apiVersion: number;\n apiVersionMinor: number;\n countryCode: string;\n isEligible: boolean;\n merchantInfo: {\n merchantId: string;\n merchantOrigin: string;\n };\n}\n\nexport interface AllowedPaymentMethods {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n billingAddressRequired: boolean;\n assuranceDetailsRequired: boolean;\n billingAddressParameters: {\n format: string;\n };\n };\n tokenizationSpecification: {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId: string;\n };\n };\n}\n\nexport type PayPalLegal = (params: { fundingSource: string }) => {\n render(container: string): void;\n};\n\nexport interface LegalFunding {\n FUNDING: {\n PAY_UPON_INVOICE: string;\n };\n}\n\nexport interface BirthDate {\n getFullYear(): number;\n getDate(): number;\n getMonth(): number;\n}\n\nexport interface PayPalCommerceScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-user-id-token'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n | 'buttons'\n | 'funding-eligibility'\n | 'hosted-fields'\n | 'messages'\n | 'payment-fields'\n | 'legal'\n | 'googlepay'\n | 'connect'\n | 'card-fields'\n>;\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalLoadScript?: (options: PayPalCommerceScriptParams) => Promise<{ paypal: PayPalSDK }>;\n}\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isAcceleratedCheckoutEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n shouldRunAcceleratedCheckout?: boolean;\n paymentButtonStyles?: Record;\n}\n\n/**\n *\n * PayPal Commerce BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Commerce Hosted Fields\n *\n */\nexport interface PayPalCommerceHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalCommerceHostedFieldOption;\n cvv?: PayPalCommerceHostedFieldOption;\n expirationDate?: PayPalCommerceHostedFieldOption;\n };\n paymentsSDK?: boolean;\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n createOrder(): Promise;\n}\n\nexport interface PayPalCommerceHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalCommerceHostedFields {\n submit(\n options?: PayPalCommerceHostedFieldsSubmitOptions,\n ): Promise;\n getState(): PayPalCommerceHostedFieldsState;\n on(eventName: string, callback: (event: PayPalCommerceHostedFieldsState) => void): void;\n}\n\nexport interface PayPalCommerceHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalCommerceHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalCommerceHostedFieldsState {\n cards: PayPalCommerceHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalCommerceHostedFieldsFieldData;\n expirationDate?: PayPalCommerceHostedFieldsFieldData;\n expirationMonth?: PayPalCommerceHostedFieldsFieldData;\n expirationYear?: PayPalCommerceHostedFieldsFieldData;\n cvv?: PayPalCommerceHostedFieldsFieldData;\n postalCode?: PayPalCommerceHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n experience?: string;\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n ): Promise | void;\n onInit?(data: InitCallbackPayload, actions: InitCallbackActions): Promise;\n onComplete?(data: CompleteCallbackDataPayload): Promise;\n onClick?(data: ClickCallbackPayload, actions: ClickCallbackActions): Promise | void;\n onError?(error: Error): void;\n onCancel?(): void;\n onShippingAddressChange?(data: ShippingAddressChangeCallbackPayload): Promise;\n onShippingOptionsChange?(data: ShippingOptionChangeCallbackPayload): Promise;\n}\n\nexport interface ShippingOptionChangeCallbackPayload {\n orderId: string;\n selectedShippingOption: PayPalSelectedShippingOption;\n}\n\nexport interface ShippingAddressChangeCallbackPayload {\n orderId: string;\n shippingAddress: PayPalAddress;\n}\n\nexport interface ClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface ClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface InitCallbackPayload {\n correlationID: string;\n}\n\nexport interface InitCallbackActions {\n disable(): void;\n enable(): void;\n}\n\nexport interface PayPalAddress {\n city: string;\n countryCode: string;\n postalCode: string;\n state: string;\n}\n\nexport interface PaypalAddressCallbackData {\n city: string;\n country_code: string;\n postal_code: string;\n state: string;\n}\n\nexport interface PayPalSelectedShippingOption {\n amount: {\n currency_code: string;\n value: string;\n };\n id: string;\n label: string;\n selected: boolean;\n type: string;\n}\n\nexport interface ApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface ApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n name: {\n full_name: string;\n };\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n address_line_2: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport interface CompleteCallbackDataPayload {\n intent: string;\n orderID: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayPalCommerce Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalCommerceMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Other\n *\n */\nexport enum NonInstantAlternativePaymentMethods {\n OXXO = 'oxxo',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n}\n\nexport interface PayPalUpdateOrderRequestBody {\n availableShippingOptions?: ShippingOption[];\n cartId: string;\n selectedShippingOption?: ShippingOption;\n}\n\nexport interface PayPalUpdateOrderResponse {\n statusCode: number;\n}\n\nexport interface PayPalCreateOrderRequestBody extends HostedInstrument, VaultedInstrument {\n cartId: string;\n metadataId?: string;\n setupToken?: boolean;\n}\n\nexport enum PayPalOrderStatus {\n Approved = 'APPROVED',\n Created = 'CREATED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n PollingStop = 'POLLING_STOP',\n PollingError = 'POLLING_ERROR',\n}\n\nexport interface PayPalOrderStatusData {\n status: PayPalOrderStatus;\n}\n\nexport interface PayPalCreateOrderCardFieldsResponse {\n orderId: string;\n setupToken?: string;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n BillingAddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n CartSource,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n RequestError,\n RequestOptions,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceRequestSender from './paypal-commerce-request-sender';\nimport PayPalCommerceScriptLoader from './paypal-commerce-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceInitializationData,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {}\n\n /**\n *\n * PayPalSDK methods\n *\n */\n async loadPayPalSdk(\n methodId: string,\n providedCurrencyCode?: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const currencyCode = providedCurrencyCode || state.getCartOrThrow().currency.code;\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.paypalSdk = await this.paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n forceLoad,\n );\n\n return this.paypalSdk;\n }\n\n getPayPalSdkOrThrow(): PayPalSDK {\n if (!this.paypalSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalSdk;\n }\n\n /**\n *\n * Buy Now cart creation methods\n *\n */\n async createBuyNowCartOrThrow(\n buyNowInitializeOptions: PayPalBuyNowInitializeOptions,\n ): Promise {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(cartRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n /**\n *\n * Order methods\n *\n */\n async createOrder(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return orderId;\n }\n\n async createOrderCardFields(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId, setupToken } = await this.paypalCommerceRequestSender.createOrder(\n providerId,\n {\n cartId,\n ...requestBody,\n },\n );\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalCommerceRequestSender.updateOrder({\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n });\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n async getOrderStatus(methodId?: string, options?: RequestOptions): Promise {\n try {\n const { status } = await this.paypalCommerceRequestSender.getOrderStatus(\n methodId,\n options,\n );\n\n return status;\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n /**\n *\n * Payment submitting and tokenizing methods\n *\n */\n tokenizePayment(methodId: string, orderId?: string): void {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n action: 'set_external_checkout',\n provider: methodId,\n order_id: orderId,\n ...(cart.source === CartSource.BuyNow && { cart_id: cart.id }),\n });\n }\n\n async submitPayment(methodId: string, orderId: string, gatewayId?: string): Promise {\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n ...(gatewayId ? { gatewayId } : {}),\n });\n }\n\n /**\n *\n * Shipping options methods\n *\n */\n getShippingOptionOrThrow(selectedShippingOptionId?: string): ShippingOption {\n const state = this.paymentIntegrationService.getState();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n const availableShippingOptions = consignment.availableShippingOptions || [];\n\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n const selectedShippingOption = selectedShippingOptionId\n ? availableShippingOptions.find((option) => option.id === selectedShippingOptionId)\n : availableShippingOptions.find(\n (option) => option.id === consignment.selectedShippingOption?.id,\n );\n\n const shippingOptionToSelect =\n selectedShippingOption || recommendedShippingOption || availableShippingOptions[0];\n\n if (!shippingOptionToSelect) {\n throw new Error(\"Your order can't be shipped to this address\");\n }\n\n return shippingOptionToSelect;\n }\n\n /**\n *\n * Address transforming methods\n *\n */\n getAddress(address?: Partial): BillingAddressRequestBody {\n return {\n firstName: address?.firstName || '',\n lastName: address?.lastName || '',\n email: address?.email || '',\n phone: '',\n company: '',\n address1: address?.address1 || '',\n address2: address?.address2 || '',\n city: address?.city || '',\n countryCode: address?.countryCode || '',\n postalCode: address?.postalCode || '',\n stateOrProvince: '',\n stateOrProvinceCode: address?.stateOrProvinceCode || '',\n customFields: [],\n };\n }\n\n getBillingAddressFromOrderDetails({ payer }: PayPalOrderDetails): BillingAddressRequestBody {\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: payer.address.address_line_1,\n address2: payer.address.address_line_2,\n city: payer.address.admin_area_2,\n countryCode: payer.address.country_code,\n postalCode: payer.address.postal_code,\n stateOrProvinceCode: payer.address.admin_area_1,\n });\n }\n\n getShippingAddressFromOrderDetails(\n orderDetails: PayPalOrderDetails,\n ): BillingAddressRequestBody {\n const { payer, purchase_units } = orderDetails;\n const {\n address,\n name: { full_name },\n } = purchase_units[0].shipping;\n\n const [firstName, ...lastName] = full_name.split(' ');\n\n return this.getAddress({\n firstName,\n lastName: lastName.join(' '),\n email: payer.email_address,\n address1: address.address_line_1,\n address2: address.address_line_2,\n city: address.admin_area_2,\n countryCode: address.country_code,\n postalCode: address.postal_code,\n stateOrProvinceCode: address.admin_area_1,\n });\n }\n\n /**\n *\n * Buttons style methods\n *\n */\n getValidButtonStyle(style?: PayPalButtonStyleOptions): PayPalButtonStyleOptions {\n const { color, height, label, shape } = style || {};\n\n const validStyles = {\n color: color && StyleButtonColor[color] ? color : undefined,\n height: this.getValidHeight(height),\n label: label && StyleButtonLabel[label] ? label : undefined,\n shape: shape && StyleButtonShape[shape] ? shape : undefined,\n };\n\n return omitBy(validStyles, isNil);\n }\n\n getValidHeight(height?: number): number {\n const defaultHeight = 40;\n const minHeight = 25;\n const maxHeight = 55;\n\n if (!height || typeof height !== 'number') {\n return defaultHeight;\n }\n\n if (height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n }\n\n /**\n *\n * Utils methods\n *\n */\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n // For now this is a temporary solution, further removeElement method will be removed\n element.style.display = 'none';\n }\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCreateOrderRequestBody,\n PayPalOrderData,\n PayPalOrderStatusData,\n PayPalUpdateOrderRequestBody,\n PayPalUpdateOrderResponse,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async createOrder(\n providerId: string,\n requestBody: Partial,\n ): Promise {\n const url = `/api/storefront/payment/${providerId}`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.post(url, { headers, body });\n\n return res.body;\n }\n\n async updateOrder(\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/paypalcommerce`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.put(url, { headers, body });\n\n return res.body;\n }\n\n async getOrderStatus(\n methodId = 'paypalcommerce',\n options?: RequestOptions,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.get(url, {\n headers,\n ...options,\n });\n\n return res.body;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n ComponentsScriptType,\n FundingType,\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.loadPayPalSDK(paypalSdkScriptConfig, forceLoad);\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const options = this.transformConfig(\n paypalSdkScriptConfig.options,\n );\n const attributes = this.transformConfig(\n paypalSdkScriptConfig.attributes,\n );\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(options).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes });\n }\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n isGooglePayEnabled,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: [\n 'buttons',\n 'hosted-fields',\n 'payment-fields',\n 'legal',\n ...googlePayComponent,\n ...cardFieldsComponent,\n ],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceIntegrationService,\n PayPalCommerceRequestSender,\n PayPalCommerceScriptLoader,\n} from './index';\n\nconst createPayPalCommerceIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n new PayPalCommerceScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createPayPalCommerceIntegrationService;\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCustomerInitializeOptions,\n ): Promise {\n const { paypalcommerce, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce.container\" argument is not provided.',\n );\n }\n\n if (paypalcommerce.onClick && typeof paypalcommerce.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce.onClick\" argument is not a function.',\n );\n }\n\n this.onError = paypalcommerce.onError || noop;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommerceCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: unknown) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCustomerInitializeOptions, {\n WithPayPalCommerceCreditCustomerInitializeOptions,\n} from './paypal-commerce-credit-customer-initialize-options';\n\nexport default class PayPalCommerceCreditCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCreditCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit.container\" argument is not provided.',\n );\n }\n\n if (paypalcommercecredit.onClick && typeof paypalcommercecredit.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit.onClick\" argument is not a function.',\n );\n }\n\n this.onError = paypalcommercecredit.onError || noop;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercecredit);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalCommerceCredit: PayPalCommerceCreditCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = paypalCommerceCredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: unknown) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCustomerStrategy from './paypal-commerce-credit-customer-strategy';\n\nconst createPayPalCommerceCreditCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCreditCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditCustomerStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoCustomerInitializeOptions, {\n WithPayPalCommerceVenmoCustomerInitializeOptions,\n} from './paypal-commerce-venmo-customer-initialize-options';\n\nexport default class PayPalCommerceVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceVenmoCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo.container\" argument is not provided.',\n );\n }\n\n if (paypalcommercevenmo.onClick && typeof paypalcommercevenmo.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo.onClick\" argument is not a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoCustomerStrategy from './paypal-commerce-venmo-customer-strategy';\n\nconst createPayPalCommerceVenmoCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoCustomerStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceSdk {\n private window: PayPalCommerceHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.paypalFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalFastlaneSdk;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.paypalApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalMessages;\n }\n\n /**\n *\n * loadPayPalSdk is a paypal sdk script loader\n * which loads paypal sdk based on provided configuration\n *\n */\n private async loadPayPalSdk({ options, attributes }: PayPalSdkConfig): Promise {\n const scriptOptions = this.transformConfig(options);\n const scriptAttributes = this.transformConfig(attributes);\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(scriptOptions).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, {\n async: true,\n attributes: scriptAttributes,\n });\n }\n\n /**\n *\n * Configurations section\n *\n */\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n attributionId,\n connectClientToken, // TODO: remove when PPCP Fastlane A/B testing will be finished\n } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-user-id-token': connectClientToken || clientToken,\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): PayPalSdkConfig {\n const { initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n } = initializationData;\n\n const enableAPMsFunding = enabledAlternativePaymentMethods;\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableAPMsFunding.length > 0 ? enableAPMsFunding : undefined,\n 'disable-funding': disableAPMsFunding.length > 0 ? disableAPMsFunding : undefined,\n commit: true,\n components: ['buttons', 'payment-fields'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-namespace': 'paypalApms',\n },\n };\n }\n\n private getPayPalSdkMessagesConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): PayPalSdkConfig {\n const { initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientId, merchantId, attributionId, isDeveloperModeApplicable, buyerCountry } =\n initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n components: ['messages'],\n currency: currencyCode,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-namespace': 'paypalMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalCommerceSdk from './paypal-commerce-sdk';\n\nexport default function createPayPalCommerceSdk(): PayPalCommerceSdk {\n return new PayPalCommerceSdk(createScriptLoader());\n}\n","import { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n fastlaneStyles?: FastlaneStylesSettings;\n connectClientToken?: string; // TODO: remove when PPCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n shouldRunAcceleratedCheckout?: boolean; // TODO: remove when PPCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * PayPalCommerceHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalCommerceHostWindow extends Window {\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n}\n\n/**\n *\n * PayPal SDK config\n *\n */\nexport interface PayPalSdkConfig {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'enable-funding'?: EnableFundingType;\n 'disable-funding'?: FundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: PayPalSdkComponents;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-user-id-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<'fastlane' | 'messages' | 'buttons' | 'payment-fields'>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalFastlaneSdk {\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: PayPalButtonApproveCallbackPayload,\n actions: PayPalButtonApproveCallbackActions,\n ): Promise | void;\n onInit?(\n data: PayPalButtonInitCallbackPayload,\n actions: PayPalButtonInitCallbackActions,\n ): Promise;\n onClick?(\n data: PayPalButtonClickCallbackPayload,\n actions: PayPalButtonClickCallbackActions,\n ): Promise | void;\n onError?(error: Error): void;\n onCancel?(): void;\n}\n\nexport interface PayPalButtonClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface PayPalButtonClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface PayPalButtonInitCallbackPayload {\n correlationID: string;\n}\n\nexport interface PayPalButtonInitCallbackActions {\n disable(): void;\n enable(): void;\n}\n\nexport interface PayPalButtonApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface PayPalButtonApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayLater Messages related types\n * doc: https://developer.paypal.com/docs/checkout/pay-later/us/integrate/reference\n */\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagesStyleOptions {\n color?: string; // 'blue' | 'black' | 'white' | 'white-no-border' | 'gray' | 'monochrome' | 'grayscale'\n layout?: string; // 'text' | 'flex'\n logo?: {\n type?: string; // 'primary' | 'alternative' | 'inline' | 'none'\n position?: string; // 'left' | 'right' | 'top'\n };\n ratio?: string; // '1x1' | '1x4' | '8x1' | '20x1'\n text?: {\n align?: string; // 'left' | 'right' | 'center'\n color?: string; // 'black' | 'white' | 'monochrome' | 'grayscale'\n size?: number; // from 10 to 16\n };\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\n}\n\n/**\n *\n * PayPal Fastlane related types\n *\n */\nexport interface PayPalFastlane {\n identity: PayPalFastlaneIdentity;\n events: PayPalFastlaneEvents;\n profile: PayPalFastlaneProfile;\n FastlaneCardComponent(\n options: PayPalFastlaneCardComponentOptions,\n ): Promise;\n}\n\nexport interface PayPalFastlaneOptions {\n styles?: PayPalFastlaneStylesOption;\n}\n\nexport interface PayPalFastlaneIdentity {\n lookupCustomerByEmail(email: string): Promise;\n triggerAuthenticationFlow(\n customerContextId: string,\n ): Promise;\n}\n\nexport interface PayPalFastlaneLookupCustomerByEmailResult {\n customerContextId?: string;\n}\n\nexport interface PayPalFastlaneAuthenticationResult {\n authenticationState?: PayPalFastlaneAuthenticationState;\n profileData?: PayPalFastlaneProfileData;\n}\n\nexport enum PayPalFastlaneAuthenticationState {\n SUCCEEDED = 'succeeded',\n FAILED = 'failed',\n CANCELED = 'cancelled',\n UNRECOGNIZED = 'unrecognized',\n}\n\nexport interface PayPalFastlaneProfileData {\n name: PayPalFastlaneProfileName;\n shippingAddress: PayPalFastlaneShippingAddress;\n card: PayPalFastlaneProfileCard;\n}\n\nexport interface PayPalFastlaneProfileName {\n fullName: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface PayPalFastlaneProfilePhone {\n countryCode: string;\n nationalNumber: string;\n}\n\nexport interface PayPalFastlaneShippingAddress {\n name: PayPalFastlaneProfileName;\n phoneNumber: PayPalFastlaneProfilePhone;\n address: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneProfileCard {\n id: string; // nonce / token\n paymentSource: PayPalFastlanePaymentSource;\n}\n\nexport interface PayPalFastlanePaymentSource {\n card: PayPalFastlaneCardSource;\n}\n\nexport interface PayPalFastlaneCardSource {\n brand: string;\n expiry: string; // \"YYYY-MM\"\n lastDigits: string; // \"1111\"\n name: string;\n billingAddress: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneAddress {\n company?: string;\n addressLine1: string;\n addressLine2?: string;\n adminArea1: string; // State\n adminArea2: string; // City\n postalCode: string;\n countryCode?: string;\n}\n\nexport interface PayPalFastlaneProfileToBcCustomerDataMappingResult {\n authenticationState: PayPalFastlaneAuthenticationState;\n addresses: CustomerAddress[];\n billingAddress?: CustomerAddress;\n shippingAddress?: CustomerAddress;\n instruments: CardInstrument[];\n}\n\nexport interface PayPalFastlaneStylesOption {\n root?: {\n backgroundColorPrimary?: string;\n errorColor?: string;\n fontFamily?: string;\n fontSizeBase?: string;\n padding?: string;\n primaryColor?: string;\n };\n input?: {\n borderRadius?: string;\n borderColor?: string;\n focusBorderColor?: string;\n backgroundColor?: string;\n borderWidth?: string;\n textColorBase?: string;\n };\n toggle?: {\n colorPrimary?: string;\n colorSecondary?: string;\n };\n text?: {\n body?: {\n color?: string;\n fontSize?: string;\n };\n caption?: {\n color?: string;\n fontSize?: string;\n };\n };\n branding?: string; // 'light' | 'dark'\n}\n\nexport interface PayPalFastlaneProfile {\n showCardSelector(): Promise;\n showShippingAddressSelector(): Promise;\n}\n\nexport interface PayPalFastlaneShippingAddressSelectorResponse {\n selectionChanged: boolean;\n selectedAddress: PayPalFastlaneShippingAddress;\n}\n\nexport interface PayPalFastlaneCardSelectorResponse {\n selectionChanged: boolean;\n selectedCard: PayPalFastlaneProfileCard;\n}\n\nexport interface PayPalFastlaneCardComponentMethods {\n getPaymentToken(\n options: PayPalFastlaneGetPaymentTokenOptions,\n ): Promise;\n render(element: string): void;\n}\n\nexport interface PayPalFastlaneGetPaymentTokenOptions {\n name?: PayPalFastlaneProfileName;\n billingAddress?: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneCardComponentOptions {\n fields?: PayPalFastlaneCardComponentFields;\n}\n\nexport interface PayPalFastlaneCardComponentFields {\n cardholderName?: {\n enabled?: boolean;\n prefill?: string;\n };\n phoneNumber?: {\n placeholder?: string;\n prefill?: string;\n };\n}\n\nexport interface PayPalFastlaneEvents {\n apmSelected: (options: PayPalFastlaneApmSelectedEventOptions) => void;\n emailSubmitted: (options: PayPalFastlaneEmailEnteredEventOptions) => void;\n orderPlaced: (options: PayPalFastlaneOrderPlacedEventOptions) => void;\n}\n\nexport interface PayPalFastlaneEventCommonOptions {\n context_type: 'cs_id';\n context_id: string; // checkout session id\n page_type: 'checkout_page';\n page_name: string; // title of the checkout initiation page\n partner_name: 'bigc';\n user_type: 'store_member' | 'store_guest'; // type of the user on the merchant site\n store_id: string;\n merchant_name: string;\n experiment: string; // stringify JSON object \"[{ treatment_group: 'test' | 'control' }]\"\n}\n\nexport interface PayPalFastlaneApmSelectedEventOptions extends PayPalFastlaneEventCommonOptions {\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page\n apm_selected: string; // alternate payment method selected / methodId\n apm_location: 'pre-email section' | 'payment section'; // placement of APM, whether it be above the email entry or in the radio buttons\n}\n\nexport interface PayPalFastlaneEmailEnteredEventOptions extends PayPalFastlaneEventCommonOptions {\n user_email_saved: boolean; // shows whether checkout was loaded with or without a saved email\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page 'applepay,googlepay,paypal'\n}\n\nexport interface PayPalFastlaneOrderPlacedEventOptions extends PayPalFastlaneEventCommonOptions {\n selected_payment_method: string;\n currency_code: string;\n}\n\nexport interface PayPalFastlanePaymentFormattedPayload {\n paypal_connect_token?: {\n order_id?: string;\n token: string;\n };\n paypal_fastlane_token?: {\n order_id?: string;\n token: string;\n };\n}\n\nexport interface FastlaneStylesSettings {\n fastlaneRootSettingsBackgroundColor?: string;\n fastlaneRootSettingsErrorColor?: string;\n fastlaneRootSettingsFontFamily?: string;\n fastlaneRootSettingsPadding?: string;\n fastlaneRootSettingsPrimaryColor?: string;\n fastlaneRootSettingsFontSize?: string;\n fastlaneInputSettingsBackgroundColor?: string;\n fastlaneInputSettingsBorderRadius?: string;\n fastlaneInputSettingsBorderWidth?: string;\n fastlaneInputSettingsTextColorBase?: string;\n fastlaneInputSettingsBorderColor?: string;\n fastlaneInputSettingsFocusBorderBase?: string;\n fastlaneToggleSettingsColorPrimary?: string;\n fastlaneToggleSettingsColorSecondary?: string;\n fastlaneTextBodySettingsColor?: string;\n fastlaneTextBodySettingsFontSize?: string;\n fastlaneTextCaptionSettingsFontSize?: string;\n fastlaneTextCaptionSettingsColor?: string;\n fastlaneBrandingSettings?: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n Address,\n CardInstrument,\n CustomerAddress,\n PaymentMethodClientUnavailableError,\n UntrustedShippingCardVerificationType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceFastlaneUtils {\n private window: PayPalCommerceHostWindow;\n\n constructor(private browserStorage: BrowserStorage) {\n this.window = window;\n }\n\n async initializePayPalFastlane(\n paypalFastlaneSdk: PayPalFastlaneSdk,\n isTestModeEnabled: boolean,\n styles?: PayPalFastlaneStylesOption,\n ): Promise {\n if (isTestModeEnabled) {\n window.localStorage.setItem('fastlaneEnv', 'sandbox');\n window.localStorage.setItem('axoEnv', 'sandbox'); // TODO: remove if this key does not use on PayPal side\n }\n\n if (!this.window.paypalFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.paypalFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.paypalFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.paypalFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalFastlane;\n }\n\n /**\n *\n * Detects the customer to PayPal Fastlane relation and\n * returns customerContextId to use it for authentication\n *\n */\n async lookupCustomerOrThrow(email: string): Promise {\n const paypalFastlane = this.getPayPalFastlaneOrThrow();\n\n return paypalFastlane.identity.lookupCustomerByEmail(email);\n }\n\n /**\n *\n * Triggers authentication flow (shows OTP popup) if the customer recognised as PayPal Fastlane user\n * and returns PayPal Fastlane Profile data to use it in BC checkout\n *\n */\n async triggerAuthenticationFlowOrThrow(\n customerContextId?: string,\n ): Promise {\n if (!customerContextId) {\n return {};\n }\n\n const paypalFastlane = this.getPayPalFastlaneOrThrow();\n\n return paypalFastlane.identity.triggerAuthenticationFlow(customerContextId);\n }\n\n /**\n *\n * 'updateStorageSessionId' method is used to:\n * - set session id after user was authenticated (or unrecognised) to trigger authentication after page refresh\n * - remove sessionId from browser storage if the customer canceled PayPal Fastlane Authentication\n *\n * Flow info:\n * If user unrecognised then the lookup method will be working but the OTP will not be shown\n * If user recognised and not canceled then the lookup method will be working and the OTP will be shown only if needed\n * If user cancels the OPT then OTP will not be triggered after page refresh\n *\n */\n updateStorageSessionId(shouldBeRemoved: boolean, sessionId?: string): void {\n if (shouldBeRemoved) {\n // TODO: Should be rewritten to cookies implementation\n this.browserStorage.removeItem('sessionId');\n } else {\n // TODO: Should be rewritten to cookies implementation\n this.browserStorage.setItem('sessionId', sessionId);\n }\n }\n\n getStorageSessionId(): string {\n // TODO: Should be rewritten to cookies implementation\n return this.browserStorage.getItem('sessionId') || '';\n }\n\n /**\n *\n * 'mapPayPalFastlaneProfileToBcCustomerData' method is responsible for:\n * - mapping PayPal Fastlane Profile data to BC data shape\n * - returning mapped data to use for updating PaymentProviderCustomer state and\n * update shipping and billing addresses\n *\n */\n mapPayPalFastlaneProfileToBcCustomerData(\n methodId: string,\n authenticationResult: PayPalFastlaneAuthenticationResult,\n ): PayPalFastlaneProfileToBcCustomerDataMappingResult {\n const { authenticationState, profileData } = authenticationResult;\n\n const paypalBillingAddress = profileData?.card?.paymentSource?.card?.billingAddress;\n const paypalShippingAddress = profileData?.shippingAddress;\n const paypalProfileName = profileData?.name;\n const paypalInstrument = profileData?.card;\n\n const shippingAddress = paypalShippingAddress\n ? this.mapPayPalToBcAddress(\n paypalShippingAddress.address,\n paypalShippingAddress.name,\n paypalShippingAddress.phoneNumber,\n )\n : undefined;\n const billingAddress =\n paypalBillingAddress && paypalProfileName\n ? this.mapPayPalToBcAddress(\n paypalBillingAddress,\n paypalProfileName,\n paypalShippingAddress?.phoneNumber,\n )\n : undefined;\n const instruments = paypalInstrument\n ? this.mapPayPalToBcInstrument(methodId, paypalInstrument)\n : [];\n\n const addresses = this.filterAddresses([shippingAddress, billingAddress]);\n\n return {\n authenticationState:\n authenticationState || PayPalFastlaneAuthenticationState.UNRECOGNIZED,\n addresses,\n billingAddress,\n shippingAddress,\n instruments,\n };\n }\n\n mapPayPalToBcInstrument(\n methodId: string,\n instrument: PayPalFastlaneProfileCard,\n ): CardInstrument[] {\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return [\n {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.PAN,\n type: 'card',\n },\n ];\n }\n\n mapBcToPayPalAddress(address?: Address): PayPalFastlaneAddress {\n return {\n company: address?.company || '',\n addressLine1: address?.address1 || '',\n addressLine2: address?.address2 || '',\n adminArea1: address?.stateOrProvinceCode || address?.stateOrProvince || '',\n adminArea2: address?.city || '',\n postalCode: address?.postalCode || '',\n countryCode: address?.countryCode || '',\n };\n }\n\n mapPayPalToBcAddress(\n address: PayPalFastlaneAddress,\n profileName: PayPalFastlaneProfileName,\n phone?: PayPalFastlaneProfilePhone,\n customFields?: CustomerAddress['customFields'],\n ): CustomerAddress {\n const [firstName, lastName] = profileName.fullName.split(' ');\n\n const phoneData = {\n nationalNumber: phone?.nationalNumber || '',\n countryCode: phone?.countryCode || '',\n };\n\n return {\n id: Date.now(),\n type: 'paypal-address',\n firstName: profileName.firstName || firstName || '',\n lastName: profileName.lastName || lastName || '',\n company: address.company || '',\n address1: address.addressLine1,\n address2: address.addressLine2 || '',\n city: address.adminArea2,\n stateOrProvince: address.adminArea1,\n stateOrProvinceCode: address.adminArea1,\n country: address.countryCode || '', // TODO: update country with valid naming\n countryCode: address.countryCode || '',\n postalCode: address.postalCode,\n phone: phoneData.countryCode + phoneData.nationalNumber,\n customFields: customFields || [],\n };\n }\n\n /**\n *\n * This method is responsible for filtering PayPal Fastlane addresses if they are the same\n * and returns an array of addresses to use them for shipping and/or billing address selections\n * so the customer will be able to use addresses from PayPal Fastlane in checkout flow\n *\n */\n filterAddresses(addresses: Array): CustomerAddress[] {\n return addresses.reduce(\n (customerAddresses: CustomerAddress[], currentAddress: CustomerAddress | undefined) => {\n if (!currentAddress) {\n return customerAddresses;\n }\n\n const sameAddressInTheArray = customerAddresses.some((customerAddress) =>\n this.isEqualAddresses(customerAddress, currentAddress),\n );\n\n return sameAddressInTheArray\n ? customerAddresses\n : [...customerAddresses, currentAddress];\n },\n [],\n );\n }\n\n private isEqualAddresses(\n firstAddress: CustomerAddress,\n secondAddress: CustomerAddress,\n ): boolean {\n return isEqual(this.normalizeAddress(firstAddress), this.normalizeAddress(secondAddress));\n }\n\n private normalizeAddress(address: CustomerAddress) {\n return omit(address, ['id', 'phone']);\n }\n}\n","import { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport PayPalCommerceFastlaneUtils from './paypal-commerce-fastlane-utils';\n\nexport default function createPayPalCommerceFastlaneUtils(): PayPalCommerceFastlaneUtils {\n return new PayPalCommerceFastlaneUtils(new BrowserStorage('paypalFastlane'));\n}\n","import { omitBy } from 'lodash';\n\nimport { FastlaneStylesSettings, PayPalFastlaneStylesOption } from '../index';\n\nfunction isInvalidStyleOption(styleOption: unknown) {\n return typeof styleOption !== 'string';\n}\n\nexport default function getFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: PayPalFastlaneStylesOption,\n) {\n if (!uiStyles && !styleSettings) {\n return undefined;\n }\n\n return cleanUpFastlaneStyles(mergeFastlaneStyles(styleSettings, uiStyles));\n}\n\nfunction mergeFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: PayPalFastlaneStylesOption,\n): PayPalFastlaneStylesOption {\n return {\n root: {\n backgroundColorPrimary:\n styleSettings?.fastlaneRootSettingsBackgroundColor ||\n uiStyles?.root?.backgroundColorPrimary,\n errorColor: styleSettings?.fastlaneRootSettingsErrorColor || uiStyles?.root?.errorColor,\n fontFamily: styleSettings?.fastlaneRootSettingsFontFamily || uiStyles?.root?.fontFamily,\n fontSizeBase:\n styleSettings?.fastlaneRootSettingsFontSize || uiStyles?.root?.fontSizeBase,\n padding: styleSettings?.fastlaneRootSettingsPadding || uiStyles?.root?.padding,\n primaryColor:\n styleSettings?.fastlaneRootSettingsPrimaryColor || uiStyles?.root?.primaryColor,\n },\n input: {\n borderRadius:\n styleSettings?.fastlaneInputSettingsBorderRadius || uiStyles?.input?.borderRadius,\n borderColor:\n styleSettings?.fastlaneInputSettingsBorderColor || uiStyles?.input?.borderColor,\n focusBorderColor:\n styleSettings?.fastlaneInputSettingsFocusBorderBase ||\n uiStyles?.input?.focusBorderColor,\n backgroundColor:\n styleSettings?.fastlaneInputSettingsBackgroundColor ||\n uiStyles?.input?.backgroundColor,\n borderWidth:\n styleSettings?.fastlaneInputSettingsBorderWidth || uiStyles?.input?.borderWidth,\n textColorBase:\n styleSettings?.fastlaneInputSettingsTextColorBase || uiStyles?.input?.textColorBase,\n },\n toggle: {\n colorPrimary:\n styleSettings?.fastlaneToggleSettingsColorPrimary || uiStyles?.toggle?.colorPrimary,\n colorSecondary:\n styleSettings?.fastlaneToggleSettingsColorSecondary ||\n uiStyles?.toggle?.colorSecondary,\n },\n text: {\n body: {\n color: styleSettings?.fastlaneTextBodySettingsColor || uiStyles?.text?.body?.color,\n fontSize:\n styleSettings?.fastlaneTextBodySettingsFontSize ||\n uiStyles?.text?.body?.fontSize,\n },\n caption: {\n color:\n styleSettings?.fastlaneTextCaptionSettingsColor ||\n uiStyles?.text?.caption?.color,\n fontSize:\n styleSettings?.fastlaneTextCaptionSettingsFontSize ||\n uiStyles?.text?.caption?.fontSize,\n },\n },\n branding: styleSettings?.fastlaneBrandingSettings || uiStyles?.branding,\n };\n}\n\nfunction cleanUpFastlaneStyles(styles: PayPalFastlaneStylesOption) {\n const fastlaneStyles: PayPalFastlaneStylesOption = {};\n\n const root = omitBy(styles.root, isInvalidStyleOption);\n const input = omitBy(styles.input, isInvalidStyleOption);\n const toggle = omitBy(styles.toggle, isInvalidStyleOption);\n const textBody = omitBy(styles.text?.body, isInvalidStyleOption);\n const textCaption = omitBy(styles.text?.caption, isInvalidStyleOption);\n const branding = styles.branding;\n\n if (Object.keys(root).length) {\n fastlaneStyles.root = root;\n }\n\n if (Object.keys(input).length) {\n fastlaneStyles.input = input;\n }\n\n if (Object.keys(toggle).length) {\n fastlaneStyles.toggle = toggle;\n }\n\n if (Object.keys(textBody).length) {\n fastlaneStyles.text = {};\n fastlaneStyles.text.body = textBody;\n }\n\n if (Object.keys(textCaption).length) {\n fastlaneStyles.text = {\n ...fastlaneStyles.text,\n };\n fastlaneStyles.text.caption = textCaption;\n }\n\n if (branding) {\n fastlaneStyles.branding = branding;\n }\n\n return fastlaneStyles;\n}\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceFastlaneCustomerInitializeOptions, {\n WithPayPalCommerceFastlaneCustomerInitializeOptions,\n} from './paypal-commerce-fastlane-customer-initialize-options';\n\nexport default class PayPalCommerceFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n try {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, paypalcommercefastlane),\n );\n } catch (_) {\n // TODO: add logger to be able to debug issues if there any\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n\n return Promise.resolve();\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const { checkoutPaymentMethodExecuted, continueWithCheckoutCallback, methodId } =\n options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomerOrThrow();\n\n if (customer.isGuest) {\n if (\n checkoutPaymentMethodExecuted &&\n typeof checkoutPaymentMethodExecuted === 'function'\n ) {\n checkoutPaymentMethodExecuted();\n }\n\n try {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n } catch (_) {\n // TODO: add logger to be able to debug issues if there any\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n }\n\n continueWithCheckoutCallback();\n }\n\n /**\n *\n * Authentication flow methods\n *\n */\n private async runPayPalAuthenticationFlowOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const customerEmail = customer?.email || billingAddress?.email || '';\n\n const { customerContextId } = await this.paypalCommerceFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cartId,\n );\n }\n\n private async updateCustomerDataState(\n methodId: string,\n authenticationResult: PayPalFastlaneAuthenticationResult,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n\n const { authenticationState, addresses, billingAddress, shippingAddress, instruments } =\n this.paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n if (billingAddress) {\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n const updatedState = await this.paymentIntegrationService.updateShippingAddress(\n shippingAddress,\n );\n\n const paymentMethod =\n updatedState.getPaymentMethodOrThrow(methodId);\n const { isFastlaneShippingOptionAutoSelectEnabled } =\n paymentMethod.initializationData || {};\n const consignments = updatedState.getConsignments() || [];\n const availableShippingOptions = consignments[0]?.availableShippingOptions || [];\n const firstShippingOption = availableShippingOptions[0];\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n if (\n (recommendedShippingOption || firstShippingOption) &&\n isFastlaneShippingOptionAutoSelectEnabled\n ) {\n const shippingOptionId = recommendedShippingOption?.id || firstShippingOption.id;\n\n await this.paymentIntegrationService.selectShippingOption(shippingOptionId);\n }\n }\n }\n\n /**\n *\n * Fastlane styling methods\n *\n */\n private getFastlaneStyles(\n methodId: string,\n paypalcommercefastlane: PayPalCommerceFastlaneCustomerInitializeOptions | undefined,\n ): PayPalFastlaneStylesOption | undefined {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const { fastlaneStyles, isFastlaneStylingEnabled } = paymentMethod.initializationData || {};\n\n return getFastlaneStyles(\n isFastlaneStylingEnabled ? fastlaneStyles : {},\n paypalcommercefastlane?.styles,\n );\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPayPalCommerceFastlaneCustomerStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // this method id will be provided for users from test group\n { id: 'paypalcommercecreditcards' }, // this method id will be provided for users from control group\n]);\n","import {\n PaymentProviderCustomer,\n StripeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isStripeAcceleratedCheckoutCustomer(\n customer: PaymentProviderCustomer,\n): customer is StripeAcceleratedCheckoutCustomer {\n return 'stripeLinkAuthenticationState' in customer;\n}\n","import { PaymentMethod } from '../stripev3/stripev3';\n\nimport { StripeUPEPaymentMethod } from './stripe-upe';\n\nexport function isStripeUPEPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripeUPEPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripeUPEPaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripeUPEPaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData\n .stripeConnectedAccount !== 'undefined' &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\n}\n","import {\n CustomFont,\n PaymentIntent,\n PaymentMethod,\n StripeConfigurationOptions,\n} from '../stripev3/stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3/stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n\n /**\n * Updates the options the Payment Element was initialized with. Updates are merged into the existing configuration.\n * https://docs.stripe.com/js/elements_object/update_payment_element\n */\n update(options?: StripeElementsCreateOptions): void;\n\n /**\n * This method collapses the Payment Element into a row of payment method tabs.\n * https://docs.stripe.com/js/elements_object/collapse_payment_element\n */\n collapse(): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: Address;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport interface StripePaymentEvent extends StripeEvent {\n value: {\n type: StripePaymentMethodType;\n };\n collapsed?: boolean;\n}\n\ninterface Address {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent | StripePaymentEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport type AddressOptions = Partial
;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n defaultCollapsed?: boolean;\n radios?: boolean;\n spacedAccordionItems?: boolean;\n visibleAccordionItemsCount?: number;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: Address;\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): Promise;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n fontFamily?: string;\n };\n\n rules?: {\n [key: string]: {\n [key: string]: string | number;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\nexport interface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n Link = 'link',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'stripe_ocs',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n\nexport enum StripeUPEPaymentIntentStatus {\n REQUIRES_PAYMENT_METHOD = 'requires_payment_method',\n REQUIRES_CONFIRMATION = 'requires_confirmation',\n REQUIRES_ACTION = 'requires_action',\n PROCESSING = 'processing',\n SUCCEEDED = 'succeeded',\n CANCELED = 'canceled',\n}\n\nexport interface StripeUPEPaymentMethod extends PaymentMethod {\n initializationData: StripeUPEInitializationData;\n}\n\nexport interface StripeUPEInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n newConfirmationFlow?: boolean;\n}\n\nexport interface StripeElementUpdateOptions {\n shouldShowTerms?: boolean;\n}\n\nexport interface StripeAdditionalActionRequired {\n type: string;\n data: {\n token?: string;\n redirect_url?: string;\n };\n}\n\nexport interface StripeAdditionalActionResponseBody {\n additional_action_required: StripeAdditionalActionRequired;\n three_ds_result: {\n token?: string;\n };\n}\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from './stripe-upe';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\nimport { WithStripeUPECustomerInitializeOptions } from './stripeupe-customer-initialize-options';\n\nexport default class StripeUPECustomerStrategy implements CustomerStrategy {\n private _stripeElements?: StripeElements;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeUPEClient;\n\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { container, gatewayId, methodId, onEmailChange, getStyles, isLoading } =\n options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { clientToken } = paymentMethod;\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n const { email } = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const stripePaymentProviderCustomer = isStripeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const stripeLinkAuthenticationState =\n stripePaymentProviderCustomer.stripeLinkAuthenticationState;\n\n if (!email) {\n let appearance: StripeUPEAppearanceOptions | undefined;\n const styles = typeof getStyles === 'function' && getStyles();\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {};\n }\n\n stripeUPEClient = await this.scriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n this._stripeElements = await this.scriptLoader.getElements(stripeUPEClient, {\n clientSecret: clientToken,\n appearance,\n });\n\n const { getBillingAddress, getConsignments } =\n this.paymentIntegrationService.getState();\n const consignments = getConsignments();\n const id = consignments?.[0]?.id;\n const { email: billingEmail } = getBillingAddress() || {};\n const options = billingEmail\n ? { defaultValues: { mode: StripeFormMode.SHIPPING, email: billingEmail } }\n : {};\n const linkAuthenticationElement =\n this._stripeElements.getElement(StripeElementType.AUTHENTICATION) ||\n this._stripeElements.create(StripeElementType.AUTHENTICATION, options);\n\n linkAuthenticationElement.on('change', (event: StripeEventType) => {\n if (!('authenticated' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingCustomer);\n }\n\n this.paymentIntegrationService.updatePaymentProviderCustomer({\n stripeLinkAuthenticationState: event.authenticated,\n });\n\n if (event.complete) {\n onEmailChange(event.authenticated, event.value.email);\n } else {\n onEmailChange(false, '');\n }\n\n if (isLoading) {\n isLoading(false);\n }\n\n if (stripeLinkAuthenticationState === undefined && event.authenticated && id) {\n this.paymentIntegrationService.deleteConsignment(id);\n }\n });\n linkAuthenticationElement.mount(`#${container}`);\n }\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.AUTHENTICATION)?.unmount();\n\n return Promise.resolve();\n }\n\n signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n signOut(options?: RequestOptions): Promise {\n this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this.stripeWindow.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeUPEClient,\n options: StripeElementsOptions,\n ): Promise {\n let stripeElements = this.stripeWindow.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this.stripeWindow, { bcStripeElements: stripeElements });\n } else {\n await this.updateStripeElements(options);\n }\n\n return stripeElements;\n }\n\n async updateStripeElements(options: StripeElementsOptions) {\n const stripeElements = this.stripeWindow.bcStripeElements;\n\n if (!stripeElements) {\n return;\n }\n\n stripeElements.update(options);\n await stripeElements.fetchUpdates();\n }\n\n private async load() {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\n","import {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCustomerStrategyFactories from '../generated/customer-strategies';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories = defaultCustomerStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry();\n\n for (const [, createCustomerStrategy] of Object.entries(customerStrategyFactories)) {\n if (\n !isResolvableModule<\n CustomerStrategyFactory,\n CustomerStrategyResolveId\n >(createCustomerStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCustomerStrategy.resolveIds) {\n registry.register(resolverId, () => createCustomerStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { ExecuteSucceededAction, SpamProtectionAction } from './spam-protection-actions';\n\nexport default function isSpamProtectionExecuteSucceededAction(\n action: SpamProtectionAction,\n): action is ExecuteSucceededAction {\n const succeededAction = action as ExecuteSucceededAction;\n\n return (\n typeof succeededAction === 'object' &&\n typeof succeededAction.payload === 'object' &&\n typeof succeededAction.payload.token === 'string'\n );\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadCheckoutAction } from '../checkout';\nimport { SpamProtectionAction } from '../spam-protection';\n\nimport Customer from './customer';\nimport { InternalCustomerResponseData } from './internal-customer-responses';\n\nexport enum CustomerActionType {\n SignInCustomerRequested = 'SIGN_IN_CUSTOMER_REQUESTED',\n SignInCustomerSucceeded = 'SIGN_IN_CUSTOMER_SUCCEEDED',\n SignInCustomerFailed = 'SIGN_IN_CUSTOMER_FAILED',\n\n SignOutCustomerRequested = 'SIGN_OUT_CUSTOMER_REQUESTED',\n SignOutCustomerSucceeded = 'SIGN_OUT_CUSTOMER_SUCCEEDED',\n SignOutCustomerFailed = 'SIGN_OUT_CUSTOMER_FAILED',\n\n CreateCustomerRequested = 'CREATE_CUSTOMER_REQUESTED',\n CreateCustomerSucceeded = 'CREATE_CUSTOMER_SUCCEEDED',\n CreateCustomerFailed = 'CREATE_CUSTOMER_FAILED',\n\n CreateCustomerAddressRequested = 'CREATE_CUSTOMER_ADDRESS_REQUESTED',\n CreateCustomerAddressSucceeded = 'CREATE_CUSTOMER_ADDRESS_SUCCEEDED',\n CreateCustomerAddressFailed = 'CREATE_CUSTOMER_ADDRESS_FAILED',\n\n StripeLinkAuthenticated = 'STRIPE_LINK_AUTHENTICATED',\n}\n\nexport type CustomerAction =\n | SignInCustomerAction\n | SignOutCustomerAction\n | CreateCustomerAddressAction\n | CreateCustomerAction;\n\nexport type CreateCustomerAction =\n | CreateCustomerRequestedAction\n | CreateCustomerSucceededAction\n | CreateCustomerFailedAction\n | SpamProtectionAction\n | LoadCheckoutAction;\n\nexport type CreateCustomerAddressAction =\n | CreateCustomerAddressRequestedAction\n | CreateCustomerAddressSucceededAction\n | CreateCustomerAddressFailedAction\n | LoadCheckoutAction;\n\nexport type SignInCustomerAction =\n | SignInCustomerRequestedAction\n | SignInCustomerSucceededAction\n | SignInCustomerFailedAction\n | LoadCheckoutAction;\n\nexport type SignOutCustomerAction =\n | SignOutCustomerRequestedAction\n | SignOutCustomerSucceededAction\n | SignOutCustomerFailedAction\n | LoadCheckoutAction;\n\nexport interface SignInCustomerRequestedAction extends Action {\n type: CustomerActionType.SignInCustomerRequested;\n}\n\nexport interface StripeLinkAuthenticatedAction extends Action {\n type: CustomerActionType.StripeLinkAuthenticated;\n}\n\nexport interface SignInCustomerSucceededAction extends Action {\n type: CustomerActionType.SignInCustomerSucceeded;\n}\n\nexport interface SignInCustomerFailedAction extends Action {\n type: CustomerActionType.SignInCustomerFailed;\n}\n\nexport interface SignOutCustomerRequestedAction extends Action {\n type: CustomerActionType.SignOutCustomerRequested;\n}\n\nexport interface SignOutCustomerSucceededAction extends Action {\n type: CustomerActionType.SignOutCustomerSucceeded;\n}\n\nexport interface SignOutCustomerFailedAction extends Action {\n type: CustomerActionType.SignOutCustomerFailed;\n}\n\nexport interface CreateCustomerRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerRequested;\n}\n\nexport interface CreateCustomerSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerSucceeded;\n}\n\nexport interface CreateCustomerFailedAction extends Action {\n type: CustomerActionType.CreateCustomerFailed;\n}\n\nexport interface CreateCustomerAddressRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressRequested;\n}\n\nexport interface CreateCustomerAddressSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerAddressSucceeded;\n}\n\nexport interface CreateCustomerAddressFailedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n isSpamProtectionExecuteSucceededAction,\n SpamProtectionActionCreator,\n} from '../spam-protection';\n\nimport CustomerAccountRequestBody, { CustomerAddressRequestBody } from './customer-account';\nimport {\n CreateCustomerAction,\n CreateCustomerAddressAction,\n CustomerActionType,\n SignInCustomerAction,\n SignOutCustomerAction,\n} from './customer-actions';\nimport CustomerCredentials from './customer-credentials';\nimport CustomerRequestSender from './customer-request-sender';\n\nexport default class CustomerActionCreator {\n constructor(\n private _customerRequestSender: CustomerRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n createCustomer(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const config = state.config.getStoreConfigOrThrow();\n const { isStorefrontSpamProtectionEnabled } = config.checkoutSettings;\n\n const createCustomer = (token?: string) =>\n from(\n this._customerRequestSender.createAccount(\n { ...customerAccount, token },\n options,\n ),\n ).pipe(\n switchMap(() =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.CreateCustomerSucceeded)),\n ),\n ),\n );\n\n return concat(\n of(createAction(CustomerActionType.CreateCustomerRequested)),\n isStorefrontSpamProtectionEnabled\n ? from(this._spamProtectionActionCreator.execute()(store)).pipe(\n switchMap((action) =>\n isSpamProtectionExecuteSucceededAction(action)\n ? concat(of(action), createCustomer(action.payload?.token))\n : of(action),\n ),\n )\n : createCustomer(),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerFailed, error),\n ),\n );\n };\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(CustomerActionType.CreateCustomerAddressRequested)),\n defer(async () => {\n const { body } = await this._customerRequestSender.createAddress(\n customerAddress,\n options,\n );\n\n return createAction(CustomerActionType.CreateCustomerAddressSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerAddressFailed, error),\n ),\n );\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(this._customerRequestSender.signInCustomer(credentials, options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.SignInCustomerSucceeded, body.data)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignInCustomerFailed, error),\n ),\n );\n }\n\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(\n createAction(\n CustomerActionType.SignOutCustomerSucceeded,\n body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignOutCustomerFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport Customer from './customer';\nimport { CustomerAccountInternalRequestBody, CustomerAddressRequestBody } from './customer-account';\nimport CustomerCredentials from './customer-credentials';\nimport { InternalCustomerResponseBody } from './internal-customer-responses';\n\nexport default class CustomerRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAccount(\n customerAccount: CustomerAccountInternalRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAccount,\n });\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/customer-address`;\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAddress,\n });\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: credentials,\n });\n }\n\n signOutCustomer({ timeout }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum CustomerStrategyActionType {\n SignInFailed = 'CUSTOMER_STRATEGY_SIGN_IN_FAILED',\n SignInRequested = 'CUSTOMER_STRATEGY_SIGN_IN_REQUESTED',\n SignInSucceeded = 'CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED',\n SignOutFailed = 'CUSTOMER_STRATEGY_SIGN_OUT_FAILED',\n SignOutRequested = 'CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED',\n SignOutSucceeded = 'CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED',\n ExecutePaymentMethodCheckoutFailed = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED',\n ExecutePaymentMethodCheckoutRequested = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED',\n ExecutePaymentMethodCheckoutSucceeded = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED',\n InitializeFailed = 'CUSTOMER_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'CUSTOMER_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'CUSTOMER_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type CustomerStrategyAction =\n | CustomerStrategySignInAction\n | CustomerStrategySignOutAction\n | CustomerStrategyExecutePaymentMethodCheckoutAction\n | CustomerStrategyInitializeAction\n | CustomerStrategyDeinitializeAction\n | CustomerStrategyWidgetAction;\n\nexport type CustomerStrategySignInAction =\n | SignInRequestedAction\n | SignInSucceededAction\n | SignInFailedAction;\n\nexport type CustomerStrategySignOutAction =\n | SignOutRequestedAction\n | SignOutSucceededAction\n | SignOutFailedAction;\n\nexport type CustomerStrategyExecutePaymentMethodCheckoutAction =\n | ExecutePaymentMethodCheckoutRequestedAction\n | ExecutePaymentMethodCheckoutSucceededAction\n | ExecutePaymentMethodCheckoutFailedAction;\n\nexport type CustomerStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type CustomerStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type CustomerStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface SignInRequestedAction extends Action {\n type: CustomerStrategyActionType.SignInRequested;\n}\n\nexport interface SignInSucceededAction extends Action {\n type: CustomerStrategyActionType.SignInSucceeded;\n}\n\nexport interface SignInFailedAction extends Action {\n type: CustomerStrategyActionType.SignInFailed;\n}\n\nexport interface SignOutRequestedAction extends Action {\n type: CustomerStrategyActionType.SignOutRequested;\n}\n\nexport interface SignOutSucceededAction extends Action {\n type: CustomerStrategyActionType.SignOutSucceeded;\n}\n\nexport interface SignOutFailedAction extends Action {\n type: CustomerStrategyActionType.SignOutFailed;\n}\n\nexport interface ExecutePaymentMethodCheckoutRequestedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested;\n}\n\nexport interface ExecutePaymentMethodCheckoutSucceededAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded;\n}\n\nexport interface ExecutePaymentMethodCheckoutFailedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: CustomerStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { CustomerStrategy as CustomerStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport CustomerCredentials from './customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from './customer-request-options';\nimport {\n CustomerStrategyActionType,\n CustomerStrategyDeinitializeAction,\n CustomerStrategyExecutePaymentMethodCheckoutAction,\n CustomerStrategyInitializeAction,\n CustomerStrategySignInAction,\n CustomerStrategySignOutAction,\n CustomerStrategyWidgetAction,\n} from './customer-strategy-actions';\nimport CustomerStrategyRegistryV2 from './customer-strategy-registry-v2';\nimport { CustomerStrategy } from './strategies';\n\nexport default class CustomerStrategyActionCreator {\n constructor(\n private _strategyRegistry: Registry,\n private _strategyRegistryV2: CustomerStrategyRegistryV2,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignInRequested, undefined, meta),\n );\n\n const promise: Promise = this._getStrategy(\n methodId,\n ).signIn(credentials, options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignInSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignInFailed, error, meta),\n );\n });\n });\n }\n\n signOut(options?: CustomerRequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignOutRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).signOut(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignOutSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignOutFailed, error, meta),\n );\n });\n });\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Observable {\n return Observable.create(\n (observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested,\n undefined,\n meta,\n ),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).executePaymentMethodCheckout(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed,\n error,\n meta,\n ),\n );\n });\n },\n );\n }\n\n initialize(\n options?: CustomerInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.InitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).initialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.InitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.InitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n deinitialize(\n options?: CustomerRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && !state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.DeinitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).deinitialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.DeinitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.DeinitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n private _getStrategy(methodId?: string): CustomerStrategy | CustomerStrategyV2 {\n let strategy: CustomerStrategy | CustomerStrategyV2;\n\n try {\n strategy = this._strategyRegistryV2.get({ id: methodId || '' });\n } catch {\n strategy = this._strategyRegistry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import joinIncludes from './join-includes';\nimport mergeIncludes from './merge-includes';\n\n/**\n * Joins or merges a base list of includes with a set of additional includes.\n */\nexport default function joinOrMergeIncludes(\n baseIncludes: T[],\n includeDictionaryOrList: { [key in T]?: boolean } | T[] = [],\n): string {\n return Array.isArray(includeDictionaryOrList)\n ? joinIncludes([...baseIncludes, ...includeDictionaryOrList])\n : mergeIncludes(baseIncludes, includeDictionaryOrList);\n}\n","import { difference, filter, keys, pickBy } from 'lodash';\n\nimport joinIncludes from './join-includes';\n\n/**\n * Merges includes given a list of base includes and a dictionary\n * of includes\n */\nexport default function mergeIncludes(\n baseIncludes: T[],\n includesDictionary?: { [key in T]?: boolean },\n): string {\n const deletions = keys(pickBy(includesDictionary, (on) => !on));\n const additions = keys(filter(includesDictionary));\n\n return joinIncludes([...difference(baseIncludes, deletions), ...additions]);\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport CHECKOUT_DEFAULT_INCLUDES from './checkout-default-includes';\nimport CheckoutParams from './checkout-params';\nimport { CheckoutNotAvailableError } from './errors';\n\nexport default class CheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadCheckout(\n id: string,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender\n .get(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n\n updateCheckout(\n id: string,\n body: CheckoutRequestBody,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadConfigAction } from '../config';\nimport { LoadFormFieldsAction } from '../form';\n\nimport Checkout from './checkout';\n\nexport enum CheckoutActionType {\n LoadCheckoutRequested = 'LOAD_CHECKOUT_REQUESTED',\n LoadCheckoutSucceeded = 'LOAD_CHECKOUT_SUCCEEDED',\n LoadCheckoutFailed = 'LOAD_CHECKOUT_FAILED',\n\n UpdateCheckoutRequested = 'UPDATE_CHECKOUT_REQUESTED',\n UpdateCheckoutSucceeded = 'UPDATE_CHECKOUT_SUCCEEDED',\n UpdateCheckoutFailed = 'UPDATE_CHECKOUT_FAILED',\n}\n\nexport type CheckoutAction = LoadCheckoutAction | UpdateCheckoutAction;\n\nexport type LoadCheckoutAction =\n | LoadCheckoutRequestedAction\n | LoadCheckoutSucceededAction\n | LoadCheckoutFailedAction\n | LoadFormFieldsAction\n | LoadConfigAction;\n\nexport type UpdateCheckoutAction =\n | UpdateCheckoutRequestedAction\n | UpdateCheckoutSucceededAction\n | UpdateCheckoutFailedAction;\n\nexport interface LoadCheckoutRequestedAction extends Action {\n type: CheckoutActionType.LoadCheckoutRequested;\n}\n\nexport interface LoadCheckoutSucceededAction extends Action {\n type: CheckoutActionType.LoadCheckoutSucceeded;\n}\n\nexport interface LoadCheckoutFailedAction extends Action {\n type: CheckoutActionType.LoadCheckoutFailed;\n}\n\nexport interface UpdateCheckoutRequestedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutRequested;\n}\n\nexport interface UpdateCheckoutSucceededAction extends Action {\n type: CheckoutActionType.UpdateCheckoutSucceeded;\n}\n\nexport interface UpdateCheckoutFailedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, merge, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator, StoreConfig } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport default class CheckoutActionCreator {\n constructor(\n private _checkoutRequestSender: CheckoutRequestSender,\n private _configActionCreator: ConfigActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n ) {}\n\n loadCheckout(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n return concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n useCache: true,\n timeout: options?.timeout,\n params: { checkoutId: id },\n }),\n this._formFieldsActionCreator.loadFormFields({\n useCache: true,\n timeout: options?.timeout,\n }),\n ),\n defer(() => {\n return this._checkoutRequestSender\n .loadCheckout(id, options)\n .then(({ body }) => {\n return createAction(\n CheckoutActionType.LoadCheckoutSucceeded,\n this._shouldTransformCustomerAddress(\n store.getState().config.getStoreConfigOrThrow(),\n )\n ? this._transformCustomerAddresses(body)\n : body,\n );\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n };\n }\n\n loadDefaultCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n useCache: true,\n timeout: options?.timeout,\n }),\n this._formFieldsActionCreator.loadFormFields({\n useCache: true,\n timeout: options?.timeout,\n }),\n ),\n defer(async () => {\n const state = store.getState();\n const context = state.config.getContextConfig();\n\n if (!context || !context.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { body } = await this._checkoutRequestSender.loadCheckout(\n context.checkoutId,\n options,\n );\n\n return createAction(\n CheckoutActionType.LoadCheckoutSucceeded,\n this._shouldTransformCustomerAddress(state.config.getStoreConfigOrThrow())\n ? this._transformCustomerAddresses(body)\n : body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n }\n\n updateCheckout(\n body: CheckoutRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CheckoutActionType.UpdateCheckoutRequested));\n\n this._checkoutRequestSender\n .updateCheckout(checkout.id, body, options)\n .then(({ body }) => {\n observer.next(\n createAction(CheckoutActionType.UpdateCheckoutSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CheckoutActionType.UpdateCheckoutFailed, response),\n );\n });\n });\n }\n\n loadCurrentCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this.loadCheckout(checkout.id, options)(store);\n };\n }\n\n private _shouldTransformCustomerAddress(storeConfig: StoreConfig): boolean {\n return (\n storeConfig.checkoutSettings.features[\n 'CHECKOUT-8183.set_shouldSaveAddress_false_for_existing_address'\n ] ?? true\n );\n }\n\n private _transformCustomerAddresses(body: Checkout): Checkout {\n return {\n ...body,\n customer: {\n ...body.customer,\n addresses: body.customer.addresses.map((address) => ({\n ...address,\n shouldSaveAddress: false,\n })),\n },\n };\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { FormFields } from './form-field';\n\nexport enum FormFieldsActionType {\n LoadFormFieldsRequested = 'LOAD_FORM_FIELDS_REQUESTED',\n LoadFormFieldsSucceeded = 'LOAD_FORM_FIELDS_SUCCEEDED',\n LoadFormFieldsFailed = 'LOAD_FORM_FIELDS_FAILED',\n}\n\nexport type LoadFormFieldsAction =\n | LoadFormFieldsRequestedAction\n | LoadFormFieldsSucceededAction\n | LoadFormFieldsFailedAction;\n\nexport interface LoadFormFieldsRequestedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsRequested;\n}\n\nexport interface LoadFormFieldsSucceededAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsSucceeded;\n}\n\nexport interface LoadFormFieldsFailedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsRequestSender from './form-fields-request-sender';\n\nexport default class FormFieldsActionCreator {\n constructor(private _formFieldsRequestSender: FormFieldsRequestSender) {}\n\n @cachableAction\n loadFormFields(options?: RequestOptions & ActionOptions): Observable {\n return concat(\n of(createAction(FormFieldsActionType.LoadFormFieldsRequested)),\n defer(async () => {\n const { body } = await this._formFieldsRequestSender.loadFields(options);\n\n return createAction(FormFieldsActionType.LoadFormFieldsSucceeded, body);\n }),\n ).pipe(\n catchError((response) =>\n throwErrorAction(FormFieldsActionType.LoadFormFieldsFailed, response),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { FormFields } from './form-field';\n\nexport default class FormFieldsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadFields({ timeout }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/form-fields';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport enum PaymentMethodActionType {\n LoadPaymentMethodRequested = 'LOAD_PAYMENT_METHOD_REQUESTED',\n LoadPaymentMethodSucceeded = 'LOAD_PAYMENT_METHOD_SUCCEEDED',\n LoadPaymentMethodFailed = 'LOAD_PAYMENT_METHOD_FAILED',\n\n LoadPaymentMethodsRequested = 'LOAD_PAYMENT_METHODS_REQUESTED',\n LoadPaymentMethodsSucceeded = 'LOAD_PAYMENT_METHODS_SUCCEEDED',\n LoadPaymentMethodsFailed = 'LOAD_PAYMENT_METHODS_FAILED',\n}\n\nexport type PaymentMethodAction = LoadPaymentMethodAction | LoadPaymentMethodsAction;\n\nexport type LoadPaymentMethodAction =\n | LoadPaymentMethodRequestedAction\n | LoadPaymentMethodSucceededAction\n | LoadPaymentMethodFailedAction;\n\nexport type LoadPaymentMethodsAction =\n | LoadPaymentMethodsRequestedAction\n | LoadPaymentMethodsSucceededAction\n | LoadPaymentMethodsFailedAction;\n\nexport interface LoadPaymentMethodRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodRequested;\n}\n\nexport interface LoadPaymentMethodSucceededAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodSucceeded;\n}\n\nexport interface LoadPaymentMethodFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodFailed;\n}\n\nexport interface LoadPaymentMethodsRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsRequested;\n}\n\nexport interface LoadPaymentMethodsSucceededAction\n extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsSucceeded;\n}\n\nexport interface LoadPaymentMethodsFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { filter } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n LoadPaymentMethodAction,\n LoadPaymentMethodsAction,\n PaymentMethodActionType,\n} from './payment-method-actions';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport { isApplePayWindow } from './strategies/apple-pay';\n\nimport { PaymentMethod } from '.';\n\nconst APPLEPAYID = 'applepay';\n\nconst isPaymentMethod = (value: PaymentMethod | undefined): value is PaymentMethod => {\n return !!value;\n};\n\nexport default class PaymentMethodActionCreator {\n constructor(private _requestSender: PaymentMethodRequestSender) {}\n\n loadPaymentMethodsById(\n methodIds: string[],\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n Promise.all(\n methodIds.map(async (id) => {\n try {\n const response = await this._requestSender.loadPaymentMethod(id, {\n ...options,\n params,\n });\n\n return response.body;\n } catch (_e) {\n return undefined;\n }\n }),\n )\n .then((response) => {\n const paymentMethods = response.filter(isPaymentMethod);\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n paymentMethods,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n observer.complete();\n });\n });\n }\n\n loadPaymentMethods(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n\n this._requestSender\n .loadPaymentMethods({\n ...options,\n params: { ...options?.params, cartId: cart.id },\n })\n .then((response) => {\n const meta = {\n deviceSessionId: response.headers['x-device-session-id'],\n sessionHash: response.headers['x-session-hash'],\n };\n const methods = response.body;\n const filteredMethods = Array.isArray(methods)\n ? this._filterApplePay(methods)\n : methods;\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n filteredMethods,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n });\n });\n }\n\n @cachableAction\n loadPaymentMethod(\n methodId: string,\n options?: RequestOptions & ActionOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(\n createAction(PaymentMethodActionType.LoadPaymentMethodRequested, undefined, {\n methodId,\n }),\n );\n\n this._requestSender\n .loadPaymentMethod(methodId, { ...options, params })\n .then((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodSucceeded,\n response.body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n private _filterApplePay(methods: PaymentMethod[]): PaymentMethod[] {\n return filter(methods, (method) => {\n if (method.id === APPLEPAYID && !isApplePayWindow(window)) {\n return false;\n }\n\n return true;\n });\n }\n}\n","export interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport PaymentMethod from './payment-method';\n\nexport default class PaymentMethodRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadPaymentMethods({ timeout, params }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/api/storefront/payments';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n loadPaymentMethod(\n methodId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${methodId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { BuyNowCartRequestBody, Cart } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class CartRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createBuyNowCart(\n body: BuyNowCartRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/carts';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body, headers, timeout });\n }\n}\n","import { isEqual } from 'lodash';\n\nimport { PartialDeep } from '../common/types';\n\nimport Cart from './cart';\n\nexport default class CartComparator {\n isEqual(cartA: Cart, cartB: Cart): boolean {\n return isEqual(this._normalize(cartA), this._normalize(cartB));\n }\n\n private _normalize(cart: Cart): PartialDeep {\n return {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n id: cart.id,\n lineItems: {\n digitalItems: cart.lineItems.digitalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n })),\n giftCertificates: cart.lineItems.giftCertificates\n .slice()\n .sort((itemA, itemB) => `${itemA.id}`.localeCompare(`${itemB.id}`))\n .map((item) => ({\n amount: item.amount,\n recipient: item.recipient,\n })),\n physicalItems: cart.lineItems.physicalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n giftWrapping: item.giftWrapping,\n })),\n },\n };\n }\n}\n","import { ComparableCheckout } from '../../checkout';\nimport { StandardError } from '../../common/error/errors';\n\nexport default class CartChangedError extends StandardError {\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n data: { previous: ComparableCheckout; updated: ComparableCheckout };\n\n constructor(previous: ComparableCheckout, updated: ComparableCheckout) {\n super(\n 'An update to your shopping cart has been detected and your available shipping costs have been updated.',\n );\n\n this.name = 'CartChangedError';\n this.type = 'cart_changed';\n this.data = {\n previous,\n updated,\n };\n }\n}\n","import { isEqual, map } from 'lodash';\n\nimport { Cart, CartComparator } from '../cart';\nimport { CartChangedError } from '../cart/errors';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { Coupon, GiftCertificate } from '../coupon';\n\nimport Checkout from './checkout';\nimport CheckoutRequestSender from './checkout-request-sender';\n\nexport type ComparableCheckout = Pick<\n Checkout,\n 'outstandingBalance' | 'coupons' | 'giftCertificates'\n> & {\n cart: Partial;\n};\n\nexport default class CheckoutValidator {\n constructor(private _checkoutRequestSender: CheckoutRequestSender) {}\n\n validate(checkout?: Checkout, options?: RequestOptions): Promise {\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this._checkoutRequestSender.loadCheckout(checkout.id, options).then((response) => {\n const comparator = new CartComparator();\n\n if (\n checkout.outstandingBalance === response.body.outstandingBalance &&\n this._compareCoupons(checkout.coupons, response.body.coupons) &&\n this._compareGiftCertificates(\n checkout.giftCertificates,\n response.body.giftCertificates,\n ) &&\n comparator.isEqual(checkout.cart, response.body.cart)\n ) {\n return;\n }\n\n throw new CartChangedError(\n this._getComparableCheckout(checkout),\n this._getComparableCheckout(response.body),\n );\n });\n }\n\n private _compareCoupons(couponsA: Coupon[], couponsB: Coupon[]): boolean {\n return isEqual(map(couponsA, 'code'), map(couponsB, 'code'));\n }\n\n private _compareGiftCertificates(\n giftCertificatesA: GiftCertificate[],\n giftCertificatesB: GiftCertificate[],\n ): boolean {\n return isEqual(map(giftCertificatesA, 'code'), map(giftCertificatesB, 'code'));\n }\n\n private _getComparableCheckout(checkout: Checkout): ComparableCheckout {\n const { cart, coupons, giftCertificates, outstandingBalance } = checkout;\n\n return {\n cart: {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n lineItems: cart.lineItems,\n },\n coupons,\n giftCertificates,\n outstandingBalance,\n };\n }\n}\n","import { StandardError } from '../../error/errors';\n\nexport default class UnexpectedDetachmentError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the required element is unexpectedly detached from the page.',\n );\n\n this.name = 'UnexpectedDetachmentError';\n this.type = 'unexpected_detachment';\n }\n}\n","import { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnexpectedDetachmentError } from './errors';\nimport { MutationObserverFactory } from './mutation-observer';\n\nexport default class DetachmentObserver {\n constructor(private _mutationObserver: MutationObserverFactory) {}\n\n async ensurePresence(targets: Node[], promise: Promise): Promise {\n const cancellable = new CancellablePromise(promise);\n\n const observer = this._mutationObserver.create((mutationsList) => {\n mutationsList.forEach((mutation) => {\n const removedTargets = Array.from(mutation.removedNodes).filter((node) =>\n targets.some((target) => node === target || node.contains(target)),\n );\n\n if (removedTargets.length === 0) {\n return;\n }\n\n cancellable.cancel(new UnexpectedDetachmentError());\n });\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n\n try {\n const output = await cancellable.promise;\n\n observer.disconnect();\n\n return output;\n } catch (error) {\n observer.disconnect();\n\n throw error;\n }\n }\n}\n","export interface MutationObeserverCreator {\n prototype: MutationObserver;\n new (callback: MutationCallback): MutationObserver;\n}\n\nexport interface MutationObserverWindow extends Window {\n MutationObserver: MutationObeserverCreator;\n}\n\nexport class MutationObserverFactory {\n constructor(private _window: MutationObserverWindow = window as MutationObserverWindow) {}\n\n create(callback: MutationCallback): MutationObserver {\n return new this._window.MutationObserver(callback);\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Url from './url';\n\nexport default function parseUrl(url: string): Url {\n if (!/^(https?:)?\\/\\//.test(url)) {\n throw new InvalidArgumentError('The provided URL must be absolute.');\n }\n\n // new URL() is not supported in IE11, use anchor tag instead\n const anchor = document.createElement('a');\n\n anchor.href = url;\n\n // IE11 returns 80 or 443 for the port number depending on the URL scheme,\n // even if the port number is not specified in the URL.\n const port =\n anchor.port && url.indexOf(`${anchor.hostname}:${anchor.port}`) !== -1 ? anchor.port : '';\n\n return {\n hash: anchor.hash,\n hostname: anchor.hostname,\n href: anchor.href,\n origin: `${anchor.protocol}//${anchor.hostname}${port ? `:${port}` : ''}`,\n pathname: anchor.pathname,\n port,\n protocol: anchor.protocol,\n search: anchor.search,\n };\n}\n","import IframeEvent from './iframe-event';\n\nexport default function isIframeEvent, TType extends string>(\n object: any,\n type: TType,\n): object is TEvent {\n return object.type === type;\n}\n","import { fromEvent } from 'rxjs';\nimport { filter, map, take } from 'rxjs/operators';\n\nimport { parseUrl } from '../url';\n\nimport IframeEvent from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport interface IframeEventPostOptions<\n TSuccessEvent extends IframeEvent,\n TErrorEvent extends IframeEvent,\n> {\n errorType?: TErrorEvent['type'];\n successType?: TSuccessEvent['type'];\n}\n\nexport default class IframeEventPoster {\n private _targetOrigin: string;\n\n constructor(targetOrigin: string, private _targetWindow?: Window, private _context?: TContext) {\n this._targetOrigin = targetOrigin === '*' ? '*' : parseUrl(targetOrigin).origin;\n }\n\n post(event: TEvent): void;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options: IframeEventPostOptions,\n ): Promise;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options?: IframeEventPostOptions,\n ): Promise | void {\n const targetWindow = this._targetWindow;\n\n if (window === targetWindow) {\n return;\n }\n\n if (!targetWindow) {\n throw new Error('Unable to post message because target window is not set.');\n }\n\n const result =\n options &&\n fromEvent(window, 'message')\n .pipe(\n filter(\n (event) =>\n event.origin === this._targetOrigin &&\n isIframeEvent(event.data, event.data.type) &&\n [options.successType, options.errorType].indexOf(event.data.type) !==\n -1,\n ),\n map((event) => {\n if (options.errorType === event.data.type) {\n throw event.data;\n }\n\n return event.data;\n }),\n take(1),\n )\n .toPromise();\n\n targetWindow.postMessage({ ...event, context: this._context }, this._targetOrigin);\n\n return result;\n }\n\n setTarget(window: Window) {\n this._targetWindow = window;\n }\n\n setContext(context: TContext) {\n this._context = context;\n }\n}\n","import parseUrl from './parse-url';\nimport Url from './url';\n\nexport default function appendWww(url: Url): Url {\n return parseUrl(\n url.hostname.indexOf('www') === 0\n ? url.href\n : url.href.replace(url.hostname, `www.${url.hostname}`),\n );\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { appendWww, parseUrl } from '../url';\n\nimport { IframeEventMap } from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport default class IframeEventListener<\n TEventMap extends IframeEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: EventListeners;\n private _sourceOrigins: string[];\n\n constructor(sourceOrigin: string) {\n this._sourceOrigins = [\n parseUrl(sourceOrigin).origin,\n appendWww(parseUrl(sourceOrigin)).origin,\n ];\n this._isListening = false;\n this._listeners = {};\n }\n\n listen(): void {\n if (this._isListening) {\n return;\n }\n\n this._isListening = true;\n\n window.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n\n window.removeEventListener('message', this._handleMessage);\n }\n\n addListener(\n type: TType,\n listener: (event: TEventMap[TType], context?: TContext) => void,\n ): void {\n let listeners = this._listeners[type];\n\n if (!listeners) {\n this._listeners[type] = listeners = [];\n }\n\n if (listeners.indexOf(listener) === -1) {\n listeners.push(listener);\n }\n }\n\n removeListener(\n type: TType,\n listener: (event: TEventMap[TType], context?: TContext) => void,\n ): void {\n const listeners = this._listeners[type];\n\n if (!listeners) {\n return;\n }\n\n const index = listeners.indexOf(listener);\n\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n }\n\n trigger(event: TEventMap[TType], context?: TContext): void {\n const listeners = this._listeners[event.type];\n\n if (!listeners) {\n return;\n }\n\n listeners.forEach((listener) => (context ? listener(event, context) : listener(event)));\n }\n\n @bind\n private _handleMessage(messageEvent: MessageEvent): void {\n if (\n this._sourceOrigins.indexOf(messageEvent.origin) === -1 ||\n !isIframeEvent(messageEvent.data as TEventMap[keyof TEventMap], messageEvent.data.type)\n ) {\n return;\n }\n\n const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n\ntype EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class SpamProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam protection challenge. Please try again.\");\n\n this.name = 'SpamProtectionChallengeNotCompletedError';\n this.type = 'spam_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class CardingProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super('Please complete our human verification challenge and try again.');\n\n this.name = 'CardingProtectionChallengeNotCompletedError';\n this.type = 'carding_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class CardingProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to verify that you are not a robot. Please try again.');\n\n this.name = 'CardingProtectionFailedError';\n this.type = 'carding_protection_failed';\n }\n}\n","import { switchMap, take } from 'rxjs/operators';\n\nimport { RequestError } from '../common/error/errors';\nimport { PaymentAdditionalAction } from '../payment';\n\nimport {\n CardingProtectionChallengeNotCompletedError,\n CardingProtectionFailedError,\n SpamProtectionChallengeNotCompletedError,\n} from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\n\nexport default class PaymentHumanVerificationHandler {\n constructor(private _googleRecaptcha: GoogleRecaptcha) {}\n\n handle(error: any): Promise;\n handle(id: string, key: string): Promise;\n async handle(errorOrId: Error | string, key?: string): Promise {\n if (typeof errorOrId === 'string') {\n return this.handleWithRecaptchaSitekey(errorOrId, key);\n }\n\n return this.handleWithPaymentHumanVerificationRequestError(errorOrId);\n }\n\n private async handleWithPaymentHumanVerificationRequestError(\n error: Error,\n ): Promise {\n if (!this._isPaymentHumanVerificationRequest(error)) {\n throw error;\n }\n\n await this._initialize(error.body.additional_action_required.data.key);\n\n return this._performRecaptcha();\n }\n\n private async handleWithRecaptchaSitekey(\n id: string,\n key?: string,\n ): Promise {\n if (id !== 'recaptcha_v2') {\n throw Error('Human verification method is not supported.');\n }\n\n if (!key) {\n throw Error('Recaptcha site key is missing.');\n }\n\n await this._initialize(key);\n\n return this._performRecaptcha();\n }\n\n private _performRecaptcha(): Promise {\n return this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw new CardingProtectionChallengeNotCompletedError();\n }\n\n if (error || !token) {\n throw new CardingProtectionFailedError();\n }\n\n return {\n type: 'recaptcha_v2_verification',\n data: {\n human_verification_token: token,\n },\n };\n }),\n )\n .toPromise();\n }\n\n private _initialize(recaptchaSitekey: string): Promise {\n const cardingProtectionElementId = 'cardingProtectionContainer';\n\n let cardingProtectionElement = document.getElementById(cardingProtectionElementId);\n\n if (cardingProtectionElement && cardingProtectionElement.parentNode) {\n cardingProtectionElement.parentNode.removeChild(cardingProtectionElement);\n }\n\n cardingProtectionElement = document.createElement('div');\n cardingProtectionElement.setAttribute('id', cardingProtectionElementId);\n document.body.appendChild(cardingProtectionElement);\n\n return this._googleRecaptcha.load(cardingProtectionElementId, recaptchaSitekey);\n }\n\n private _isPaymentHumanVerificationRequest(error: Error): error is RequestError {\n const { additional_action_required, status } = (error as RequestError).body || {};\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'recaptcha_v2_verification'\n );\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class SpamProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to complete your spam protection verification. Please try again.');\n\n this.name = 'SpamProtectionFailedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if spam protection is not loaded when trying to\n * complete the required spam protection verification.\n */\nexport default class SpamProtectionNotLoadedError extends StandardError {\n constructor() {\n super('Spam protection is not loaded. Please try again.');\n\n this.name = 'SpamProtectionNotLoadedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { defer, Observable, of, Subject, throwError } from 'rxjs';\nimport { catchError, delay, retryWhen, switchMap } from 'rxjs/operators';\n\nimport { MutationObserverFactory } from '../common/dom';\nimport { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport {\n SpamProtectionChallengeNotCompletedError,\n SpamProtectionFailedError,\n SpamProtectionNotLoadedError,\n} from './errors';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nconst TIMEOUT = 7000;\nconst RETRY_INTERVAL = 250;\nconst MAX_RETRIES = TIMEOUT / RETRY_INTERVAL;\n\nexport interface RecaptchaResult {\n error?: Error;\n token?: string;\n}\n\nexport default class GoogleRecaptcha {\n private _event$?: Subject;\n private _recaptcha?: ReCaptchaV2.ReCaptcha;\n private _memoized: (\n recaptcha: ReCaptchaV2.ReCaptcha,\n sitekey: string,\n container: HTMLElement | null,\n ) => Subject;\n private _widgetId?: number;\n\n constructor(\n private googleRecaptchaScriptLoader: GoogleRecaptchaScriptLoader,\n private mutationObserverFactory: MutationObserverFactory,\n ) {\n this._memoized = memoize(\n (recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => {\n const event$ = new Subject();\n\n if (!container) {\n throw new Error();\n }\n\n this._widgetId = recaptcha.render(container.id, {\n sitekey,\n size: 'invisible',\n callback: () => {\n event$.next({\n token: recaptcha.getResponse(this._widgetId),\n });\n recaptcha.reset(this._widgetId);\n },\n 'error-callback': () => {\n event$.next({\n error: new SpamProtectionFailedError(),\n });\n },\n });\n\n return event$;\n },\n { isEqual: (a, b) => a === b },\n );\n }\n\n load(containerId: string, sitekey: string): Promise {\n return this.googleRecaptchaScriptLoader.load().then((recaptcha) => {\n if (recaptcha) {\n this._event$ = this._memoized(\n recaptcha,\n sitekey,\n document.getElementById(containerId),\n );\n this._recaptcha = recaptcha;\n }\n });\n }\n\n execute(): Observable {\n return defer(() => {\n const event$ = this._event$;\n const recaptcha = this._recaptcha;\n\n if (!event$ || !recaptcha) {\n throw new NotInitializedError(NotInitializedErrorType.SpamProtectionNotInitialized);\n }\n\n return defer(() => {\n const element = document.querySelector('iframe[src*=\"bframe\"]');\n\n return element ? of(element) : throwError(new SpamProtectionNotLoadedError());\n }).pipe(\n retryWhen((errors) =>\n errors.pipe(\n delay(RETRY_INTERVAL),\n switchMap((error, index) =>\n index < MAX_RETRIES ? of(error) : throwError(error),\n ),\n ),\n ),\n switchMap((element) => {\n this._watchRecaptchaChallengeWindow(event$, element);\n recaptcha.execute(this._widgetId);\n\n return event$;\n }),\n catchError((error) => of({ error })),\n );\n });\n }\n\n private _watchRecaptchaChallengeWindow(event: Subject, element: Element) {\n const iframeContainer = element.parentElement;\n\n if (!iframeContainer) {\n throw new SpamProtectionNotLoadedError();\n }\n\n const container = iframeContainer.parentElement;\n\n if (!container) {\n throw new SpamProtectionNotLoadedError();\n }\n\n this.mutationObserverFactory\n .create(() => {\n // When customer closes the Google ReCaptcha challenge window, throw SpamProtectionNotCompletedError\n if (container.style.visibility === 'hidden') {\n event.next({\n error: new SpamProtectionChallengeNotCompletedError(),\n });\n }\n })\n .observe(container, { attributes: true, attributeFilter: ['style'] });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nexport default class GoogleRecaptchaScriptLoader {\n private _loadPromise?: Promise;\n\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GoogleRecaptchaWindow = window,\n ) {}\n\n load(): Promise {\n if (!this._loadPromise) {\n this._loadPromise = this._loadScript();\n }\n\n return this._loadPromise;\n }\n\n private _loadScript(): Promise {\n const callbackName = 'initRecaptcha';\n const params = [`onload=${callbackName}`, 'render=explicit'].join('&');\n\n return new Promise((resolve, reject) => {\n this._window[callbackName] = () => resolve(this._window.grecaptcha);\n\n this._scriptLoader\n .loadScript(`//www.google.com/recaptcha/api.js?${params}`)\n .catch((error) => {\n this._loadPromise = undefined;\n reject(error);\n });\n });\n }\n}\n\nexport interface GoogleRecaptchaWindow extends Window {\n grecaptcha?: ReCaptchaV2.ReCaptcha;\n initRecaptcha?(): void;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { MutationObserverFactory } from '../common/dom';\n\nimport GoogleRecaptcha from './google-recaptcha';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nexport default function createSpamProtection(scriptLoader: ScriptLoader): GoogleRecaptcha {\n return new GoogleRecaptcha(\n new GoogleRecaptchaScriptLoader(scriptLoader),\n new MutationObserverFactory(),\n );\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromPaymentErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || message,\n errors,\n });\n}\n\nfunction joinErrors(errors: Array<{ code: string; message?: string }>): string | undefined {\n if (!Array.isArray(errors)) {\n return;\n }\n\n return errors\n .reduce((result: string[], error) => {\n if (error && error.message) {\n return [...result, error.message];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed due to invalid configuration provided for the hosted payment form.',\n );\n\n this.name = 'InvalidHostedFormConfigError';\n this.type = 'invalid_hosted_form_config';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to an unknown error with the hosted payment form.');\n\n this.name = 'InvalidHostedFormError';\n this.type = 'invalid_hosted_form';\n }\n}\n","import { flatMap, map, values } from 'lodash';\n\nimport { StandardError } from '../../common/error/errors';\nimport { HostedInputValidateErrorDataMap } from '../iframe-content';\n\nexport default class InvalidHostedFormValueError extends StandardError {\n constructor(public errors: HostedInputValidateErrorDataMap) {\n super(\n [\n 'Unable to proceed due to invalid user input values',\n ...flatMap(values(errors), (fieldErrors) =>\n map(fieldErrors, ({ message }) => message),\n ),\n ].join('. '),\n );\n\n this.name = 'InvalidHostedFormValueError';\n this.type = 'invalid_hosted_form_value';\n }\n}\n","import { CardInstrument } from '../payment/instrument';\n\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport enum HostedFieldEventType {\n AttachRequested = 'HOSTED_FIELD:ATTACH_REQUESTED',\n SubmitRequested = 'HOSTED_FIELD:SUBMITTED_REQUESTED',\n ValidateRequested = 'HOSTED_FIELD:VALIDATE_REQUESTED',\n StoredCardRequested = 'HOSTED_FIELD:STORED_CARD_REQUESTED',\n}\n\nexport interface HostedFieldEventMap {\n [HostedFieldEventType.AttachRequested]: HostedFieldAttachEvent;\n [HostedFieldEventType.SubmitRequested]: HostedFieldSubmitRequestEvent;\n [HostedFieldEventType.ValidateRequested]: HostedFieldValidateRequestEvent;\n [HostedFieldEventType.StoredCardRequested]: HostedFieldStoredCardRequestEvent;\n}\n\nexport type HostedFieldEvent =\n | HostedFieldAttachEvent\n | HostedFieldSubmitRequestEvent\n | HostedFieldValidateRequestEvent\n | HostedFieldStoredCardRequestEvent;\n\nexport interface HostedFieldAttachEvent {\n type: HostedFieldEventType.AttachRequested;\n payload: {\n accessibilityLabel?: string;\n cardInstrument?: CardInstrument;\n fontUrls?: string[];\n placeholder?: string;\n styles?: HostedFieldStylesMap;\n origin?: string;\n type: HostedFieldType;\n };\n}\n\nexport interface HostedFieldSubmitRequestEvent {\n type: HostedFieldEventType.SubmitRequested;\n payload: {\n data: HostedFormOrderData;\n fields: HostedFieldType[];\n };\n}\n\nexport interface HostedFieldValidateRequestEvent {\n type: HostedFieldEventType.ValidateRequested;\n}\n\nexport interface HostedFieldStoredCardRequestEvent {\n type: HostedFieldEventType.StoredCardRequested;\n payload: {\n data: StoredCardHostedFormData;\n fields: StoredCardHostedFormInstrumentFields;\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport {\n PaymentErrorData,\n PaymentErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HostedFieldType from '../hosted-field-type';\nimport { HostedFormErrorsData } from '../hosted-form-options';\n\nimport HostedInputInitializeErrorData from './hosted-input-initialize-error-data';\nimport HostedInputValidateResults from './hosted-input-validate-results';\n\n// Event types\nexport enum HostedInputEventType {\n AttachSucceeded = 'HOSTED_INPUT:ATTACH_SUCCEEDED',\n AttachFailed = 'HOSTED_INPUT:ATTACH_FAILED',\n BinChanged = 'HOSTED_INPUT:BIN_CHANGED',\n Blurred = 'HOSTED_INPUT:BLURRED',\n Changed = 'HOSTED_INPUT:CHANGED',\n CardTypeChanged = 'HOSTED_INPUT:CARD_TYPE_CHANGED',\n Entered = 'HOSTED_INPUT:ENTERED',\n Focused = 'HOSTED_INPUT:FOCUSED',\n SubmitSucceeded = 'HOSTED_INPUT:SUBMIT_SUCCEEDED',\n SubmitFailed = 'HOSTED_INPUT:SUBMIT_FAILED',\n Validated = 'HOSTED_INPUT:VALIDATED',\n StoredCardSucceeded = 'HOSTED_INPUT:STORED_CARD_SUCCEEDED',\n StoredCardFailed = 'HOSTED_INPUT:STORED_CARD_FAILED',\n}\n\n// Event mapping\nexport interface HostedInputEventMap {\n [HostedInputEventType.AttachSucceeded]: HostedInputAttachSuccessEvent;\n [HostedInputEventType.AttachFailed]: HostedInputAttachErrorEvent;\n [HostedInputEventType.BinChanged]: HostedInputBinChangeEvent;\n [HostedInputEventType.Blurred]: HostedInputBlurEvent;\n [HostedInputEventType.Changed]: HostedInputChangeEvent;\n [HostedInputEventType.CardTypeChanged]: HostedInputCardTypeChangeEvent;\n [HostedInputEventType.Entered]: HostedInputEnterEvent;\n [HostedInputEventType.Focused]: HostedInputFocusEvent;\n [HostedInputEventType.SubmitSucceeded]: HostedInputSubmitSuccessEvent;\n [HostedInputEventType.SubmitFailed]: HostedInputSubmitErrorEvent;\n [HostedInputEventType.Validated]: HostedInputValidateEvent;\n [HostedInputEventType.StoredCardFailed]: HostedInputStoredCardErrorEvent;\n [HostedInputEventType.StoredCardSucceeded]: HostedInputStoredCardSucceededEvent;\n}\n\n// Events\nexport type HostedInputEvent =\n | HostedInputAttachSuccessEvent\n | HostedInputAttachErrorEvent\n | HostedInputBinChangeEvent\n | HostedInputBlurEvent\n | HostedInputChangeEvent\n | HostedInputCardTypeChangeEvent\n | HostedInputEnterEvent\n | HostedInputFocusEvent\n | HostedInputSubmitSuccessEvent\n | HostedInputSubmitErrorEvent\n | HostedInputValidateEvent\n | HostedInputStoredCardSucceededEvent\n | HostedInputStoredCardErrorEvent;\n\nexport interface HostedInputAttachSuccessEvent {\n type: HostedInputEventType.AttachSucceeded;\n}\n\nexport interface HostedInputStoredCardSucceededEvent {\n type: HostedInputEventType.StoredCardSucceeded;\n}\n\nexport interface HostedInputStoredCardErrorEvent {\n type: HostedInputEventType.StoredCardFailed;\n payload?: {\n errors?: string[];\n error?: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputAttachErrorEvent {\n type: HostedInputEventType.AttachFailed;\n payload: {\n error: HostedInputInitializeErrorData;\n };\n}\n\nexport interface HostedInputBinChangeEvent {\n type: HostedInputEventType.BinChanged;\n payload: {\n bin?: string;\n };\n}\n\nexport interface HostedInputBlurEvent {\n type: HostedInputEventType.Blurred;\n payload: {\n fieldType: HostedFieldType;\n errors?: HostedFormErrorsData;\n };\n}\n\nexport interface HostedInputChangeEvent {\n type: HostedInputEventType.Changed;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputCardTypeChangeEvent {\n type: HostedInputEventType.CardTypeChanged;\n payload: {\n cardType?: string;\n };\n}\n\nexport interface HostedInputFocusEvent {\n type: HostedInputEventType.Focused;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputEnterEvent {\n type: HostedInputEventType.Entered;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputSubmitSuccessEvent {\n type: HostedInputEventType.SubmitSucceeded;\n payload: {\n response: Response;\n };\n}\n\nexport interface HostedInputSubmitErrorEvent {\n type: HostedInputEventType.SubmitFailed;\n payload: {\n error: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputValidateEvent {\n type: HostedInputEventType.Validated;\n payload: HostedInputValidateResults;\n}\n","import { values } from 'lodash';\nimport { fromEvent } from 'rxjs';\nimport { switchMap, take } from 'rxjs/operators';\n\nimport { DetachmentObserver } from '../common/dom';\nimport { mapFromPaymentErrorResponse } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { parseUrl } from '../common/url';\nimport { CardInstrument } from '../payment/instrument';\n\nimport {\n InvalidHostedFormConfigError,\n InvalidHostedFormError,\n InvalidHostedFormValueError,\n} from './errors';\nimport { HostedFieldEvent, HostedFieldEventType } from './hosted-field-events';\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputStoredCardSucceededEvent,\n HostedInputSubmitErrorEvent,\n HostedInputSubmitSuccessEvent,\n HostedInputValidateEvent,\n} from './iframe-content';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport const RETRY_INTERVAL = 60 * 1000;\nexport const LAST_RETRY_KEY = 'lastRetry';\n\nexport default class HostedField {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _type: HostedFieldType,\n private _containerId: string,\n private _placeholder: string,\n private _accessibilityLabel: string,\n private _styles: HostedFieldStylesMap,\n private _eventPoster: IframeEventPoster,\n private _eventListener: IframeEventListener,\n private _detachmentObserver: DetachmentObserver,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n this._iframe.src = `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n getType(): HostedFieldType {\n return this._type;\n }\n\n async attach(): Promise {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the provided container ID is not valid.',\n );\n }\n\n container.appendChild(this._iframe);\n this._eventListener.listen();\n\n const promise = fromEvent(this._iframe, 'load')\n .pipe(\n switchMap(async ({ target }) => {\n const contentWindow = target && (target as HTMLIFrameElement).contentWindow;\n\n if (!contentWindow) {\n throw new Error('The content window of the iframe cannot be accessed.');\n }\n\n this._eventPoster.setTarget(contentWindow);\n\n await this._eventPoster.post(\n {\n type: HostedFieldEventType.AttachRequested,\n payload: {\n accessibilityLabel: this._accessibilityLabel,\n cardInstrument: this._cardInstrument,\n fontUrls: this._getFontUrls(),\n placeholder: this._placeholder,\n styles: this._styles,\n origin: document.location.origin,\n type: this._type,\n },\n },\n {\n successType: HostedInputEventType.AttachSucceeded,\n errorType: HostedInputEventType.AttachFailed,\n },\n );\n }),\n take(1),\n )\n .toPromise();\n\n await this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n this._eventListener.stopListen();\n }\n\n async submitForm(\n fields: HostedFieldType[],\n data: HostedFormOrderData,\n ): Promise {\n try {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.SubmitRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.SubmitSucceeded,\n errorType: HostedInputEventType.SubmitFailed,\n },\n );\n\n return await this._detachmentObserver.ensurePresence([this._iframe], promise);\n } catch (event) {\n if (this._isSubmitErrorEvent(event)) {\n if (event.payload.error.code === 'hosted_form_error') {\n throw new InvalidHostedFormError(event.payload.error.message);\n }\n\n if (event.payload.response) {\n throw mapFromPaymentErrorResponse(event.payload.response);\n }\n\n throw new Error(event.payload.error.message);\n }\n\n throw event;\n }\n }\n\n async submitStoredCardForm(\n fields: StoredCardHostedFormInstrumentFields,\n data: StoredCardHostedFormData,\n ): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.StoredCardRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.StoredCardSucceeded,\n errorType: HostedInputEventType.StoredCardFailed,\n },\n );\n\n return this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n async validateForm(): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.ValidateRequested,\n },\n {\n successType: HostedInputEventType.Validated,\n },\n );\n\n const { payload } = await this._detachmentObserver.ensurePresence([this._iframe], promise);\n\n if (!payload.isValid) {\n throw new InvalidHostedFormValueError(payload.errors);\n }\n }\n\n private _getFontUrls(): string[] {\n const hostname = 'fonts.googleapis.com';\n const links = document.querySelectorAll(`link[href*='${hostname}'][rel='stylesheet']`);\n\n return Array.prototype.slice\n .call(links)\n .filter((link) => parseUrl(link.href).hostname === hostname)\n .filter((link) =>\n values(this._styles)\n .map((style) => style && style.fontFamily)\n .filter((family): family is string => typeof family === 'string')\n .some((family) =>\n family\n .split(/,\\s/)\n .some((name) => link.href.indexOf(name.replace(' ', '+')) !== -1),\n ),\n )\n .map((link) => link.href);\n }\n\n private _isSubmitErrorEvent(event: any): event is HostedInputSubmitErrorEvent {\n return event.type === HostedInputEventType.SubmitFailed;\n }\n}\n","import { noop, without } from 'lodash';\n\nimport { HostedForm as HostedFormInterface } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener } from '../common/iframe';\nimport { OrderPaymentRequestBody } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport { InvalidHostedFormConfigError } from './errors';\nimport HostedField from './hosted-field';\nimport LegacyHostedFormOptions from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\nimport {\n HostedInputEnterEvent,\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputStoredCardSucceededEvent,\n HostedInputSubmitSuccessEvent,\n} from './iframe-content';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\ntype HostedFormEventCallbacks = Pick<\n LegacyHostedFormOptions,\n 'onBlur' | 'onCardTypeChange' | 'onFocus' | 'onEnter' | 'onValidate'\n>;\n\nexport default class HostedForm implements HostedFormInterface {\n private _bin?: string;\n private _cardType?: string;\n\n constructor(\n private _fields: HostedField[],\n private _eventListener: IframeEventListener,\n private _payloadTransformer: HostedFormOrderDataTransformer,\n private _eventCallbacks: HostedFormEventCallbacks,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {\n const {\n onBlur = noop,\n onCardTypeChange = noop,\n onFocus = noop,\n onValidate = noop,\n } = this._eventCallbacks;\n\n this._eventListener.addListener(HostedInputEventType.Blurred, ({ payload }) =>\n onBlur(payload),\n );\n this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) =>\n onCardTypeChange(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Focused, ({ payload }) =>\n onFocus(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Validated, ({ payload }) =>\n onValidate(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Entered, this._handleEnter);\n\n this._eventListener.addListener(\n HostedInputEventType.CardTypeChanged,\n ({ payload }) => (this._cardType = payload.cardType),\n );\n this._eventListener.addListener(\n HostedInputEventType.BinChanged,\n ({ payload }) => (this._bin = payload.bin),\n );\n }\n\n getBin(): string | undefined {\n return this._bin;\n }\n\n getCardType(): string | undefined {\n return this._cardType;\n }\n\n async attach(): Promise {\n this._eventListener.listen();\n\n const field = this._getFirstField();\n const otherFields = without(this._fields, field);\n\n await field.attach();\n await Promise.all(otherFields.map((otherField) => otherField.attach()));\n }\n\n detach(): void {\n this._eventListener.stopListen();\n\n this._fields.forEach((field) => {\n field.detach();\n });\n }\n\n async submit(\n payload: OrderPaymentRequestBody,\n additionalActionData?: PaymentAdditionalAction,\n ): Promise {\n try {\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalActionData),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalAction),\n );\n }\n }\n\n async submitStoredCard(payload: {\n fields: StoredCardHostedFormInstrumentFields;\n data: StoredCardHostedFormData;\n }): Promise {\n return this._getFirstField().submitStoredCardForm(payload.fields, payload.data);\n }\n\n async validate(): Promise {\n return this._getFirstField().validateForm();\n }\n\n private _getFirstField(): HostedField {\n const field = this._fields[0];\n\n if (!field) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the payment form has no field defined.',\n );\n }\n\n return field;\n }\n\n private _handleEnter: (event: HostedInputEnterEvent) => Promise = async ({ payload }) => {\n try {\n await this.validate();\n } catch (error) {\n // Catch form validation error because we want to trigger `onEnter`\n // irrespective of the validation result.\n if (error instanceof Error && error.name !== 'InvalidHostedFormValueError') {\n throw error;\n }\n }\n\n const { onEnter = noop } = this._eventCallbacks;\n\n onEnter(payload);\n };\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import { omit } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { OrderPaymentRequestBody } from '../order';\nimport {\n HostedCreditCardInstrument,\n isVaultedInstrument,\n PaymentAdditionalAction,\n} from '../payment';\n\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport default class HostedFormOrderDataTransformer {\n constructor(private _store: ReadableCheckoutStore) {}\n\n transform(\n payload: OrderPaymentRequestBody,\n additionalAction?: PaymentAdditionalAction,\n ): HostedFormOrderData {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const config = state.config.getConfig();\n const instrumentMeta = state.instruments.getInstrumentsMeta();\n const order = state.order.getOrder();\n const orderMeta = state.order.getOrderMeta();\n const payment = omit(\n payload.paymentData,\n 'ccExpiry',\n 'ccName',\n 'ccNumber',\n 'ccCvv',\n ) as HostedCreditCardInstrument;\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n const paymentMethodMeta = state.paymentMethods.getPaymentMethodsMeta();\n const authToken =\n instrumentMeta && payment && isVaultedInstrument(payment)\n ? `${state.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : state.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment,\n paymentMethod,\n paymentMethodMeta,\n };\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\nimport { pick } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { CardInstrument } from '../payment/instrument';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport HostedField from './hosted-field';\nimport HostedFieldType from './hosted-field-type';\nimport HostedForm from './hosted-form';\nimport LegacyHostedFormOptions, {\n HostedCardFieldOptionsMap,\n HostedStoredCardFieldOptionsMap,\n} from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\n\nexport default class HostedFormFactory {\n constructor(private _store: ReadableCheckoutStore) {}\n\n create(host: string, options: LegacyHostedFormOptions): HostedForm {\n const fieldTypes = Object.keys(options.fields) as HostedFieldType[];\n const fields = fieldTypes.reduce((result, type) => {\n const fields = options.fields as HostedStoredCardFieldOptionsMap &\n HostedCardFieldOptionsMap;\n const fieldOptions = fields[type];\n\n if (!fieldOptions) {\n return result;\n }\n\n return [\n ...result,\n new HostedField(\n type,\n fieldOptions.containerId,\n fieldOptions.placeholder || '',\n fieldOptions.accessibilityLabel || '',\n options.styles || {},\n new IframeEventPoster(host),\n new IframeEventListener(host),\n new DetachmentObserver(new MutationObserverFactory()),\n 'instrumentId' in fieldOptions\n ? this._getCardInstrument(fieldOptions.instrumentId)\n : undefined,\n ),\n ];\n }, []);\n\n return new HostedForm(\n fields,\n new IframeEventListener(host),\n new HostedFormOrderDataTransformer(this._store),\n pick(options, 'onBlur', 'onEnter', 'onFocus', 'onCardTypeChange', 'onValidate'),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n }\n\n private _getCardInstrument(instrumentId: string): CardInstrument {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const instrument = getCardInstrument(instrumentId);\n\n if (!instrument) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentInstrument);\n }\n\n return instrument;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam check.\n */\nexport default class SpamProtectionNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam check. Please try again.\");\n\n this.name = 'SpamProtectionNotCompletedError';\n this.type = 'spam_protection_not_completed';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { InternalOrderResponseData } from './internal-order-responses';\nimport Order from './order';\n\nexport enum OrderActionType {\n LoadOrderRequested = 'LOAD_ORDER_REQUESTED',\n LoadOrderSucceeded = 'LOAD_ORDER_SUCCEEDED',\n LoadOrderFailed = 'LOAD_ORDER_FAILED',\n\n LoadOrderPaymentsRequested = 'LOAD_ORDER_PAYMENTS_REQUESTED',\n LoadOrderPaymentsSucceeded = 'LOAD_ORDER_PAYMENTS_SUCCEEDED',\n LoadOrderPaymentsFailed = 'LOAD_ORDER_PAYMENTS_FAILED',\n\n SubmitOrderRequested = 'SUBMIT_ORDER_REQUESTED',\n SubmitOrderSucceeded = 'SUBMIT_ORDER_SUCCEEDED',\n SubmitOrderFailed = 'SUBMIT_ORDER_FAILED',\n\n FinalizeOrderRequested = 'FINALIZE_ORDER_REQUESTED',\n FinalizeOrderSucceeded = 'FINALIZE_ORDER_SUCCEEDED',\n FinalizeOrderFailed = 'FINALIZE_ORDER_FAILED',\n}\n\nexport type OrderAction =\n | LoadOrderAction\n | LoadOrderPaymentsAction\n | SubmitOrderAction\n | FinalizeOrderAction;\n\nexport type LoadOrderPaymentsAction =\n | LoadOrderPaymentsRequestedAction\n | LoadOrderPaymentsSucceededAction\n | LoadOrderPaymentsFailedAction;\n\nexport type LoadOrderAction =\n | LoadOrderRequestedAction\n | LoadOrderSucceededAction\n | LoadOrderFailedAction;\n\nexport type SubmitOrderAction =\n | SubmitOrderRequestedAction\n | SubmitOrderSucceededAction\n | SubmitOrderFailedAction\n | LoadOrderAction;\n\nexport type FinalizeOrderAction =\n | FinalizeOrderRequestedAction\n | FinalizeOrderSucceededAction\n | FinalizeOrderFailedAction\n | LoadOrderAction;\n\nexport interface LoadOrderRequestedAction extends Action {\n type: OrderActionType.LoadOrderRequested;\n}\n\nexport interface LoadOrderSucceededAction extends Action {\n type: OrderActionType.LoadOrderSucceeded;\n}\n\nexport interface LoadOrderFailedAction extends Action {\n type: OrderActionType.LoadOrderFailed;\n}\n\nexport interface LoadOrderPaymentsRequestedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsRequested;\n}\n\nexport interface LoadOrderPaymentsSucceededAction extends Action {\n type: OrderActionType.LoadOrderPaymentsSucceeded;\n}\n\nexport interface LoadOrderPaymentsFailedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsFailed;\n}\n\nexport interface SubmitOrderRequestedAction extends Action {\n type: OrderActionType.SubmitOrderRequested;\n}\n\nexport interface SubmitOrderSucceededAction extends Action {\n type: OrderActionType.SubmitOrderSucceeded;\n}\n\nexport interface SubmitOrderFailedAction extends Action {\n type: OrderActionType.SubmitOrderFailed;\n}\n\nexport interface FinalizeOrderRequestedAction extends Action {\n type: OrderActionType.FinalizeOrderRequested;\n}\n\nexport interface FinalizeOrderSucceededAction extends Action {\n type: OrderActionType.FinalizeOrderSucceeded;\n}\n\nexport interface FinalizeOrderFailedAction extends Action {\n type: OrderActionType.FinalizeOrderFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, Observer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutValidator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { SpamProtectionNotCompletedError } from '../spam-protection/errors';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport {\n FinalizeOrderAction,\n LoadOrderAction,\n LoadOrderPaymentsAction,\n OrderActionType,\n SubmitOrderAction,\n} from './order-actions';\nimport OrderRequestBody from './order-request-body';\nimport OrderRequestSender from './order-request-sender';\n\nexport default class OrderActionCreator {\n constructor(\n private _orderRequestSender: OrderRequestSender,\n private _checkoutValidator: CheckoutValidator,\n ) {}\n\n loadOrder(orderId: number, options?: RequestOptions): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(createAction(OrderActionType.LoadOrderSucceeded, response.body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(OrderActionType.LoadOrderFailed, response));\n });\n });\n }\n\n // TODO: Remove when checkout does not contain unrelated order data.\n loadOrderPayments(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderPaymentsRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(\n createAction(OrderActionType.LoadOrderPaymentsSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(OrderActionType.LoadOrderPaymentsFailed, response),\n );\n });\n });\n }\n\n loadCurrentOrder(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n defer(() => {\n const orderId = this._getCurrentOrderId(store.getState());\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.loadOrder(orderId, options);\n });\n }\n\n submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(OrderActionType.SubmitOrderRequested)),\n defer(() => {\n const state = store.getState();\n const externalSource = state.config.getExternalSource();\n const variantIdentificationToken = state.config.getVariantIdentificationToken();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (checkout.shouldExecuteSpamCheck) {\n throw new SpamProtectionNotCompletedError();\n }\n\n return from(\n this._checkoutValidator.validate(checkout, options).then(() =>\n this._orderRequestSender.submitOrder(\n this._mapToOrderRequestBody(\n payload ?? {},\n checkout.id,\n checkout.customerMessage,\n externalSource,\n ),\n {\n ...options,\n headers: {\n checkoutVariant: variantIdentificationToken,\n },\n },\n ),\n ),\n ).pipe(\n switchMap((response) =>\n concat(\n // TODO: Remove once we can submit orders using storefront API\n this.loadOrder(response.body.data.order.orderId, options),\n of(\n createAction(\n OrderActionType.SubmitOrderSucceeded,\n response.body.data,\n { ...response.body.meta, token: response.headers.token },\n ),\n ),\n ),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(OrderActionType.SubmitOrderFailed, error),\n ),\n ),\n );\n }\n\n finalizeOrder(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(OrderActionType.FinalizeOrderRequested)),\n from(this._orderRequestSender.finalizeOrder(orderId, options)).pipe(\n switchMap((response) =>\n concat(\n this.loadOrder(orderId, options),\n of(\n createAction(\n OrderActionType.FinalizeOrderSucceeded,\n response.body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(catchError((error) => throwErrorAction(OrderActionType.FinalizeOrderFailed, error)));\n }\n\n private _getCurrentOrderId(state: InternalCheckoutSelectors): number | undefined {\n const order = state.order.getOrder();\n const checkout = state.checkout.getCheckout();\n\n return (order && order.orderId) || (checkout && checkout.orderId);\n }\n\n private _mapToOrderRequestBody(\n payload: OrderRequestBody,\n cartId: string,\n customerMessage: string,\n externalSource?: string,\n ): InternalOrderRequestBody {\n const { payment, ...order } = payload;\n\n if (!payment) {\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n };\n }\n\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n payment: {\n paymentData: payment.paymentData,\n name: payment.methodId,\n gateway: payment.gatewayId,\n },\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when the server detects inconsistency in cart data since it is last requested,\n * for example, product prices or eligible discounts have changed.\n */\nexport default class CartConsistencyError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because some details have changed. Please review your order and try again.',\n );\n\n this.name = 'CartConsistencyError';\n this.type = 'cart_consistency';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Checkout prevents consumers from placing their orders when a merchant wishes\n * to be able to block transactions if the automated tax provider cannot be reached.\n */\nexport default class OrderTaxProviderUnavailableError extends StandardError {\n constructor(message?: string) {\n super(message || 'The tax provider is unavailable.');\n\n this.name = 'OrderTaxProviderUnavailableError';\n this.type = 'tax_provider_unavailable';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport { CartConsistencyError } from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { OrderTaxProviderUnavailableError } from './errors';\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { InternalOrderResponseBody } from './internal-order-responses';\nimport Order from './order';\n\nexport interface SubmitOrderRequestOptions extends RequestOptions {\n headers?: {\n checkoutVariant?: string;\n };\n}\n\nexport default class OrderRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadOrder(orderId: number, { timeout }: RequestOptions = {}): Promise> {\n const url = `/api/storefront/orders/${orderId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = [\n 'payments',\n 'lineItems.physicalItems.socialMedia',\n 'lineItems.physicalItems.options',\n 'lineItems.physicalItems.categories',\n 'lineItems.digitalItems.socialMedia',\n 'lineItems.digitalItems.options',\n 'lineItems.digitalItems.categories',\n ];\n\n return this._requestSender.get(url, {\n params: {\n include: joinIncludes(include),\n },\n headers,\n timeout,\n });\n }\n\n submitOrder(\n body?: InternalOrderRequestBody,\n { headers, timeout }: SubmitOrderRequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/order';\n\n return this._requestSender\n .post(url, {\n body,\n headers: omitBy(\n {\n 'X-Checkout-Variant': headers && headers.checkoutVariant,\n ...SDK_VERSION_HEADERS,\n },\n isNil,\n ),\n timeout,\n })\n .catch((error) => {\n if (error.body.type === 'tax_provider_unavailable') {\n throw new OrderTaxProviderUnavailableError();\n }\n\n if (error.body.type === 'cart_has_changed') {\n throw new CartConsistencyError();\n }\n\n throw error;\n });\n }\n\n finalizeOrder(\n orderId: number,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/internalapi/v1/checkout/order/${orderId}`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderAction } from '../order';\n\nimport PaymentResponseBody from './payment-response-body';\n\nexport enum PaymentActionType {\n SubmitPaymentRequested = 'SUBMIT_PAYMENT_REQUESTED',\n SubmitPaymentSucceeded = 'SUBMIT_PAYMENT_SUCCEEDED',\n SubmitPaymentFailed = 'SUBMIT_PAYMENT_FAILED',\n\n InitializeOffsitePaymentRequested = 'INITIALIZE_OFFSITE_PAYMENT_REQUESTED',\n InitializeOffsitePaymentSucceeded = 'INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED',\n InitializeOffsitePaymentFailed = 'INITIALIZE_OFFSITE_PAYMENT_FAILED',\n}\n\nexport type PaymentAction = SubmitPaymentAction | InitializeOffsitePaymentAction;\n\nexport type SubmitPaymentAction =\n | SubmitPaymentRequestedAction\n | SubmitPaymentSucceededAction\n | SubmitPaymentFailedAction\n | LoadOrderAction;\n\nexport type InitializeOffsitePaymentAction =\n | InitializeOffsitePaymentRequestedAction\n | InitializeOffsitePaymentSucceededAction\n | InitializeOffsitePaymentFailedAction;\n\nexport interface SubmitPaymentRequestedAction extends Action {\n type: PaymentActionType.SubmitPaymentRequested;\n}\n\nexport interface SubmitPaymentSucceededAction extends Action {\n type: PaymentActionType.SubmitPaymentSucceeded;\n}\n\nexport interface SubmitPaymentFailedAction extends Action {\n type: PaymentActionType.SubmitPaymentFailed;\n}\n\nexport interface InitializeOffsitePaymentRequestedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentRequested;\n}\n\nexport interface InitializeOffsitePaymentSucceededAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentSucceeded;\n}\n\nexport interface InitializeOffsitePaymentFailedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { OrderActionCreator } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport Payment, {\n FormattedHostedInstrument,\n FormattedPayload,\n FormattedVaultedInstrument,\n} from './payment';\nimport {\n InitializeOffsitePaymentAction,\n PaymentActionType,\n SubmitPaymentAction,\n} from './payment-actions';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\n\ninterface InitializeOffsitePaymentSettings {\n methodId: string;\n gatewayId?: string;\n instrumentId?: string;\n target?: string;\n promise?: Promise;\n shouldSaveInstrument?: boolean;\n shouldSetAsDefaultInstrument?: boolean;\n}\n\ntype InitializeOffsitePayment = (\n settings: InitializeOffsitePaymentSettings,\n) => ThunkAction;\n\nexport default class PaymentActionCreator {\n constructor(\n private _paymentRequestSender: PaymentRequestSender,\n private _orderActionCreator: OrderActionCreator,\n private _paymentRequestTransformer: PaymentRequestTransformer,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n submitPayment(payment: Payment): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentActionType.SubmitPaymentRequested)),\n defer(async () => {\n try {\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(payment, store.getState()),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(\n error,\n );\n\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(\n { ...payment, additionalAction },\n store.getState(),\n ),\n );\n }\n }).pipe(\n switchMap(({ body }) =>\n concat(\n this._orderActionCreator.loadCurrentOrder()(store),\n of(createAction(PaymentActionType.SubmitPaymentSucceeded, body)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.SubmitPaymentFailed, error),\n ),\n );\n }\n\n initializeOffsitePayment: InitializeOffsitePayment = ({\n methodId,\n gatewayId,\n instrumentId,\n target,\n promise,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n }) => {\n return (store) => {\n let paymentData:\n | FormattedPayload\n | undefined;\n\n if (instrumentId) {\n paymentData = { formattedPayload: { bigpay_token: instrumentId } };\n } else if (shouldSaveInstrument) {\n paymentData = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n };\n }\n\n const payload = this._paymentRequestTransformer.transform(\n { gatewayId, methodId, paymentData },\n store.getState(),\n );\n\n return concat(\n of(createAction(PaymentActionType.InitializeOffsitePaymentRequested)),\n Promise.race(\n [\n this._paymentRequestSender.initializeOffsitePayment(payload, target),\n promise,\n ].filter(Boolean),\n ).then(() => createAction(PaymentActionType.InitializeOffsitePaymentSucceeded)),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.InitializeOffsitePaymentFailed, error),\n ),\n );\n };\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentRequestBody from './payment-request-body';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class PaymentRequestSender {\n /**\n * @class\n * @param {BigpayClient} client\n */\n constructor(private _client: any) {}\n\n submitPayment(payload: PaymentRequestBody): Promise> {\n return new Promise((resolve, reject) => {\n this._client.submitPayment(payload, (error: any, response: any) => {\n if (error) {\n reject(this._transformResponse(error));\n } else {\n resolve(this._transformResponse(response));\n }\n });\n });\n }\n\n initializeOffsitePayment(payload: PaymentRequestBody, target?: string): Promise {\n return new Promise(() => {\n this._client.initializeOffsitePayment(payload, null, target);\n });\n }\n\n private _transformResponse(response: any): Response {\n return {\n headers: response.headers,\n body: response.data,\n status: response.status,\n statusText: response.statusText,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/bigpay-client\");","// / \nimport { createClient as createBigpayClient } from '@bigcommerce/bigpay-client';\n\nimport { CheckoutStore } from '../checkout';\n\nexport default function createPaymentClient(store: CheckoutStore) {\n const paymentClient = createBigpayClient();\n\n store.subscribe(\n (state) => {\n const config = state.config.getStoreConfig();\n\n if (config) {\n paymentClient.setHost(config.paymentSettings.bigpayBaseUrl);\n }\n },\n (state) => state.config.getStoreConfig(),\n );\n\n return paymentClient;\n}\n","import { BillingAddress, isBillingAddressLike } from '../billing';\nimport { Consignment } from '../shipping';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalAddress(\n address: Address | BillingAddress,\n consignments?: Consignment[],\n): InternalAddress {\n let addressId;\n\n if (isBillingAddressLike(address)) {\n addressId = address.id;\n } else if (consignments && consignments.length) {\n addressId = consignments[0].id;\n }\n\n return {\n id: addressId,\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n addressLine1: address.address1,\n addressLine2: address.address2,\n city: address.city,\n province: address.stateOrProvince,\n provinceCode: address.stateOrProvinceCode,\n postCode: address.postalCode,\n country: address.country,\n countryCode: address.countryCode,\n phone: address.phone,\n customFields: address.customFields,\n };\n}\n","import { Address } from '../address';\n\nimport BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: Address): address is BillingAddress {\n const billingAddress = address as BillingAddress;\n\n return typeof billingAddress.id !== 'undefined';\n}\n","export default class AmountTransformer {\n constructor(private _decimalPlaces: number) {}\n\n toInteger(amount: number): number {\n return Math.round(amount * 10 ** this._decimalPlaces);\n }\n}\n","import Coupon from './coupon';\nimport InternalCoupon from './internal-coupon';\n\nconst couponTypes = [\n 'per_item_discount',\n 'percentage_discount',\n 'per_total_discount',\n 'shipping_discount',\n 'free_shipping',\n];\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {\n return {\n code: coupon.code,\n discount: coupon.displayName,\n discountType: couponTypes.indexOf(coupon.couponType),\n };\n}\n","import GiftCertificate from './gift-certificate';\nimport InternalGiftCertificate from './internal-gift-certificate';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalGiftCertificate(\n giftCertificate: GiftCertificate,\n): InternalGiftCertificate {\n return {\n code: giftCertificate.code,\n discountedAmount: giftCertificate.used,\n remainingBalance: giftCertificate.remaining,\n giftCertificate: {\n balance: giftCertificate.balance,\n code: giftCertificate.code,\n purchaseDate: giftCertificate.purchaseDate,\n },\n };\n}\n","enum CheckoutButtonMethodType {\n APPLEPAY = \"applepay\",\n AMAZON_PAY_V2 = \"amazonpay\",\n BRAINTREE_PAYPAL = \"braintreepaypal\",\n BRAINTREE_VENMO = \"braintreevenmo\",\n BRAINTREE_PAYPAL_CREDIT = \"braintreepaypalcredit\",\n GOOGLEPAY_ADYENV2 = \"googlepayadyenv2\",\n GOOGLEPAY_ADYENV3 = \"googlepayadyenv3\",\n GOOGLEPAY_AUTHORIZENET = \"googlepayauthorizenet\",\n GOOGLEPAY_BNZ = \"googlepaybnz\",\n GOOGLEPAY_BRAINTREE = \"googlepaybraintree\",\n GOOGLEPAY_CHECKOUTCOM = \"googlepaycheckoutcom\",\n GOOGLEPAY_CYBERSOURCEV2 = \"googlepaycybersourcev2\",\n GOOGLEPAY_ORBITAL = \"googlepayorbital\",\n GOOGLEPAY_STRIPE = \"googlepaystripe\",\n GOOGLEPAY_STRIPEUPE = \"googlepaystripeupe\",\n GOOGLEPAY_WORLDPAYACCESS = \"googlepayworldpayaccess\",\n MASTERPASS = \"masterpass\",\n PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\n\n","import InternalLineItem from './internal-line-item';\nimport { LineItem } from './line-item';\nimport LineItemMap from './line-item-map';\nimport mapGiftCertificateToInternalLineItem from './map-gift-certificate-to-internal-line-item';\nimport mapToInternalLineItem from './map-to-internal-line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItems(\n itemMap: LineItemMap,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem[] {\n return (Object.keys(itemMap) as Array).reduce(\n (result, key) => [\n ...result,\n ...(itemMap[key] as LineItem[]).map((item: any) => {\n if (key === 'giftCertificates') {\n return mapGiftCertificateToInternalLineItem(item, decimalPlaces);\n }\n\n return mapToInternalLineItem(\n item,\n mapToInternalLineItemType(key),\n decimalPlaces,\n idKey,\n );\n }),\n ],\n [] as InternalLineItem[],\n );\n}\n\nfunction mapToInternalLineItemType(type: string): string {\n switch (type) {\n case 'physicalItems':\n return 'ItemPhysicalEntity';\n\n case 'digitalItems':\n return 'ItemDigitalEntity';\n\n case 'giftCertificates':\n return 'ItemGiftCertificateEntity';\n\n default:\n return '';\n }\n}\n","import { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport InternalLineItem from './internal-line-item';\nimport { GiftCertificateItem } from './line-item';\n\nexport default function mapGiftCertificateToInternalLineItem(\n item: GiftCertificateItem,\n decimalPlaces: number,\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item.id,\n imageUrl: '',\n name: item.name,\n amount: item.amount,\n amountAfterDiscount: item.amount,\n discount: 0,\n integerAmount: amountTransformer.toInteger(item.amount),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.amount),\n integerUnitPrice: amountTransformer.toInteger(item.amount),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.amount),\n integerDiscount: 0,\n quantity: 1,\n sender: item.sender,\n recipient: item.recipient,\n type: 'ItemGiftCertificateEntity',\n attributes: [],\n variantId: null,\n };\n}\n","import { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport InternalLineItem from './internal-line-item';\nimport { DigitalItem, LineItem } from './line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItem(\n item: LineItem,\n type: string,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item[idKey] as string | number,\n imageUrl: item.imageUrl,\n amount: item.extendedListPrice,\n amountAfterDiscount: item.extendedSalePrice,\n discount: item.discountAmount,\n integerAmount: amountTransformer.toInteger(item.extendedListPrice),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.extendedSalePrice),\n integerDiscount: amountTransformer.toInteger(item.discountAmount),\n integerUnitPrice: amountTransformer.toInteger(item.listPrice),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.salePrice),\n downloadsPageUrl: (item as DigitalItem).downloadPageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: item.brand,\n sku: item.sku,\n categoryNames: item.categoryNames,\n variantId: item.variantId,\n productId: item.productId,\n attributes: (item.options || []).map((option) => ({\n name: option.name,\n value: option.value,\n })),\n addedByPromotion: item.addedByPromotion,\n type,\n };\n}\n","import { keyBy, reduce, some } from 'lodash';\n\nimport { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { mapToInternalCoupon, mapToInternalGiftCertificate } from '../coupon';\nimport { mapToDiscountNotifications } from '../promotion';\n\nimport InternalCart from './internal-cart';\nimport mapToInternalLineItems from './map-to-internal-line-items';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCart(checkout: Checkout): InternalCart {\n const decimalPlaces = checkout.cart.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: checkout.cart.id,\n items: mapToInternalLineItems(checkout.cart.lineItems, decimalPlaces),\n currency: checkout.cart.currency.code,\n coupon: {\n discountedAmount: reduce(\n checkout.cart.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: checkout.cart.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: checkout.cart.discountAmount,\n integerAmount: amountTransformer.toInteger(checkout.cart.discountAmount),\n },\n discountNotifications: mapToDiscountNotifications(checkout.promotions),\n giftCertificate: {\n totalDiscountedAmount: reduce(\n checkout.giftCertificates,\n (sum, certificate) => {\n return sum + certificate.used;\n },\n 0,\n ),\n appliedGiftCertificates: keyBy(\n checkout.giftCertificates.map(mapToInternalGiftCertificate),\n 'code',\n ),\n },\n shipping: {\n amount: checkout.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.shippingCostTotal),\n amountBeforeDiscount: checkout.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n checkout.shippingCostBeforeDiscount,\n ),\n required: some(\n checkout.cart.lineItems.physicalItems,\n (lineItem) => lineItem.isShippingRequired,\n ),\n },\n subtotal: {\n amount: checkout.subtotal,\n integerAmount: amountTransformer.toInteger(checkout.subtotal),\n },\n storeCredit: {\n amount: checkout.customer ? checkout.customer.storeCredit : 0,\n },\n taxSubtotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n taxes: checkout.taxes,\n taxTotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n handling: {\n amount: checkout.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.handlingCostTotal),\n },\n grandTotal: {\n amount: checkout.grandTotal,\n integerAmount: amountTransformer.toInteger(checkout.grandTotal),\n },\n };\n}\n","import { DiscountNotification } from '../discount';\n\nimport { Promotion } from '.';\n\nexport default function mapToDiscountNotifications(\n promotions?: Promotion[],\n): DiscountNotification[] {\n const notifications: DiscountNotification[] = [];\n\n (promotions || []).forEach((promotion) => {\n (promotion.banners || []).forEach((banner) => {\n notifications.push({\n placeholders: [],\n discountType: null,\n message: '',\n messageHtml: banner.text,\n });\n });\n });\n\n return notifications;\n}\n","import { mapToInternalAddress } from '../address';\nimport { OrderBillingAddress } from '../order-billing-address/order-billing-address-state';\n\nimport InternalCustomer from './internal-customer';\n\nimport { Customer } from '.';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCustomer(\n customer: Customer,\n billingAddress: OrderBillingAddress,\n): InternalCustomer {\n const firstName = customer.firstName || billingAddress.firstName || '';\n const lastName = customer.lastName || billingAddress.lastName || '';\n\n return {\n addresses: (customer.addresses || []).map((address) => mapToInternalAddress(address)),\n customerId: customer.id,\n isGuest: customer.isGuest,\n storeCredit: customer.storeCredit,\n email: customer.email || billingAddress.email || '',\n firstName,\n lastName,\n name: customer.fullName || [firstName, lastName].join(' '),\n customerGroupName: customer.customerGroup && customer.customerGroup.name,\n };\n}\n","import CardExpiryDate from './card-expiry-date';\n\nconst NUMBER_SEPARATOR = '/';\n\nexport default class CardExpiryFormatter {\n format(value: string): string {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n const trimmedMonth = month.slice(0, 2);\n const trimmedYear =\n year.length === 4 ? year.slice(-2) : year ? year.slice(0, 2) : month.slice(2);\n\n // i.e.: '1'\n if (value.length < 2) {\n return month;\n }\n\n // ie.: '10 /' (without trailing space)\n if (value.length > 3 && !trimmedYear) {\n return trimmedMonth;\n }\n\n return `${trimmedMonth} ${NUMBER_SEPARATOR} ${trimmedYear}`;\n }\n\n toObject(value: string): CardExpiryDate {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n\n if (!/^\\d+$/.test(month) || !/^\\d+$/.test(year)) {\n return { month: '', year: '' };\n }\n\n return {\n month: month.length === 1 ? `0${month}` : month.slice(0, 2),\n year: year.length === 2 ? `20${year}` : year.slice(0, 4),\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"card-validator\");","import { creditCardType, number } from 'card-validator';\nimport { max } from 'lodash';\n\nconst NUMBER_SEPARATOR = ' ';\n\nexport default class CardNumberFormatter {\n format(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n const maxLength = max(creditCardType(value).map((info) => max(info.lengths)));\n const unformattedValue = this.unformat(value).slice(0, maxLength);\n\n return card.gaps\n .filter((gapIndex) => unformattedValue.length > gapIndex)\n .reduce(\n (output, gapIndex, index) =>\n [output.slice(0, gapIndex + index), output.slice(gapIndex + index)].join(\n NUMBER_SEPARATOR,\n ),\n unformattedValue,\n );\n }\n\n unformat(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n return value.replace(new RegExp(NUMBER_SEPARATOR, 'g'), '');\n }\n}\n","import { filter, find, keyBy, reduce } from 'lodash';\n\nimport { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { LineItem, mapToInternalLineItems } from '../cart';\nimport { Checkout } from '../checkout';\nimport { mapToInternalCoupon } from '../coupon';\nimport { HOSTED } from '../payment';\n\nimport InternalOrder, {\n InternalGiftCertificateList,\n InternalIncompleteOrder,\n InternalOrderPayment,\n InternalSocialDataList,\n} from './internal-order';\nimport Order, {\n GatewayOrderPayment,\n GiftCertificateOrderPayment,\n OrderPayment,\n OrderPayments,\n} from './order';\nimport { OrderMetaState } from './order-state';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalOrder(\n order: Order,\n orderMeta: OrderMetaState = {},\n): InternalOrder {\n const decimalPlaces = order.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: order.orderId,\n items: mapToInternalLineItems(order.lineItems, order.currency.decimalPlaces, 'productId'),\n orderId: order.orderId,\n currency: order.currency.code,\n customerCanBeCreated: order.customerCanBeCreated,\n payment: mapToInternalOrderPayment(order.payments, orderMeta.payment),\n subtotal: {\n amount: order.baseAmount,\n integerAmount: amountTransformer.toInteger(order.baseAmount),\n },\n coupon: {\n discountedAmount: reduce(\n order.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: order.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: order.discountAmount,\n integerAmount: amountTransformer.toInteger(order.discountAmount),\n },\n token: orderMeta.orderToken,\n callbackUrl: orderMeta.callbackUrl,\n discountNotifications: [],\n giftCertificate: mapToGiftCertificates(order.payments),\n socialData: mapToInternalSocialDataList(order),\n status: order.status,\n hasDigitalItems: order.hasDigitalItems,\n isDownloadable: order.isDownloadable,\n isComplete: order.isComplete,\n shipping: {\n amount: order.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(order.shippingCostTotal),\n amountBeforeDiscount: order.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n order.shippingCostBeforeDiscount,\n ),\n },\n storeCredit: {\n amount: mapToStoreCredit(order.payments),\n },\n taxes: order.taxes,\n taxTotal: {\n amount: order.taxTotal,\n integerAmount: amountTransformer.toInteger(order.taxTotal),\n },\n handling: {\n amount: order.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(order.handlingCostTotal),\n },\n grandTotal: {\n amount: order.orderAmount,\n integerAmount: order.orderAmountAsInteger,\n },\n };\n}\n\nexport function mapToInternalIncompleteOrder(checkout: Checkout): InternalIncompleteOrder {\n const payment = find(checkout.payments, { providerType: HOSTED });\n\n return {\n orderId: null,\n isComplete: false,\n payment: !payment\n ? {}\n : {\n id: payment.providerId,\n gateway: payment.gatewayId,\n status: mapToInternalPaymentStatus(payment.detail.step),\n },\n };\n}\n\nfunction mapToInternalPaymentStatus(status: string): string {\n return `PAYMENT_STATUS_${status}`;\n}\n\nfunction mapToStoreCredit(payments?: OrderPayments): number {\n const item = find(payments, { providerId: 'storecredit' });\n\n return item ? item.amount : 0;\n}\n\nfunction mapToGiftCertificates(payments?: OrderPayments): InternalGiftCertificateList {\n const items = filter(payments, {\n providerId: 'giftcertificate',\n }) as GiftCertificateOrderPayment[];\n\n return {\n totalDiscountedAmount: reduce(items, (sum, item) => item.amount + sum, 0),\n appliedGiftCertificates: keyBy(\n items.map((item) => ({\n code: item.detail.code,\n discountedAmount: item.amount,\n remainingBalance: item.detail.remaining,\n giftCertificate: {\n balance: item.amount + item.detail.remaining,\n code: item.detail.code,\n purchaseDate: '',\n },\n })),\n 'code',\n ),\n };\n}\n\nfunction mapToInternalOrderPayment(\n payments?: OrderPayments,\n payment: InternalOrderPayment = {},\n): InternalOrderPayment {\n const item = find(payments, isDefaultOrderPayment) as GatewayOrderPayment;\n\n if (!item) {\n return {};\n }\n\n return {\n id: item.providerId,\n status: mapToInternalPaymentStatus(item.detail.step),\n helpText: item.detail.instructions,\n returnUrl: payment.returnUrl,\n };\n}\n\nfunction isDefaultOrderPayment(payment: OrderPayment): payment is GatewayOrderPayment {\n return payment.providerId !== 'giftcertificate' && payment.providerId !== 'storecredit';\n}\n\nfunction mapToInternalSocialDataList(\n order: Order,\n): { [itemId: string]: InternalSocialDataList } | undefined {\n const socialDataObject: { [itemId: string]: InternalSocialDataList } = {};\n const items = [...order.lineItems.physicalItems, ...order.lineItems.digitalItems];\n\n items.forEach((item) => {\n socialDataObject[item.id] = mapToInternalSocialData(item);\n });\n\n return socialDataObject;\n}\n\nfunction mapToInternalSocialData(lineItem: LineItem): InternalSocialDataList {\n const codes = ['fb', 'tw', 'gp'];\n\n return codes.reduce((socialData, code) => {\n const item =\n lineItem.socialMedia && find(lineItem.socialMedia, (item) => item.code === code);\n\n if (!item) {\n return socialData;\n }\n\n socialData[code] = {\n name: lineItem.name,\n description: lineItem.name,\n image: lineItem.imageUrl,\n url: item.link,\n shareText: item.text,\n sharingLink: item.link,\n channelName: item.channel,\n channelCode: item.code,\n };\n\n return socialData;\n }, {} as InternalSocialDataList);\n}\n","import InternalShippingOption from './internal-shipping-option';\nimport ShippingOption from './shipping-option';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalShippingOption(\n option: ShippingOption,\n isSelected: boolean,\n): InternalShippingOption {\n return {\n description: option.description,\n module: option.type,\n price: option.cost,\n id: option.id,\n selected: isSelected,\n isRecommended: option.isRecommended,\n imageUrl: option.imageUrl,\n transitTime: option.transitTime,\n };\n}\n","import { pick } from 'lodash';\n\nimport { Address, mapToInternalAddress } from '../address';\nimport { mapToInternalCart } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { CheckoutButtonMethodType } from '../checkout-buttons/strategies';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { mapToInternalCustomer } from '../customer';\nimport { HostedFormOrderData } from '../hosted-form';\nimport {\n CardExpiryFormatter,\n CardNumberFormatter,\n HostedInputValues,\n} from '../hosted-form/iframe-content';\nimport { mapToInternalOrder } from '../order';\nimport { mapToInternalShippingOption } from '../shipping';\n\nimport isVaultedInstrument, { isFormattedVaultedInstrument } from './is-vaulted-instrument';\nimport Payment, {\n HostedCreditCardInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n} from './payment';\nimport PaymentMethod from './payment-method';\nimport PaymentRequestBody from './payment-request-body';\n\nexport default class PaymentRequestTransformer {\n private _cardExpiryFormatter = new CardExpiryFormatter();\n private _cardNumberFormatter = new CardNumberFormatter();\n\n transform(payment: Payment, checkoutState: InternalCheckoutSelectors): PaymentRequestBody {\n const billingAddress = checkoutState.billingAddress.getBillingAddress();\n const checkout = checkoutState.checkout.getCheckout();\n const customer = checkoutState.customer.getCustomer();\n const order = checkoutState.order.getOrder();\n const paymentMethod = checkoutState.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n const shippingAddress = this._mapShippingAddress(checkoutState, paymentMethod);\n const consignments = checkoutState.consignments.getConsignments();\n const shippingOption = checkoutState.consignments.getShippingOption();\n const storeConfig = checkoutState.config.getStoreConfig();\n const contextConfig = checkoutState.config.getContextConfig();\n const instrumentMeta = checkoutState.instruments.getInstrumentsMeta();\n const paymentMeta = checkoutState.paymentMethods.getPaymentMethodsMeta();\n const orderMeta = checkoutState.order.getOrderMeta();\n const internalCustomer =\n customer && billingAddress && mapToInternalCustomer(customer, billingAddress);\n\n const authToken =\n instrumentMeta &&\n payment.paymentData &&\n (isVaultedInstrument(payment.paymentData) ||\n isFormattedVaultedInstrument(payment.paymentData))\n ? `${checkoutState.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : checkoutState.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction: payment.additionalAction,\n authToken,\n customer: internalCustomer,\n billingAddress: billingAddress && mapToInternalAddress(billingAddress),\n shippingAddress: shippingAddress && mapToInternalAddress(shippingAddress, consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: payment.paymentData,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n quoteMeta: {\n request: {\n ...paymentMeta,\n geoCountryCode: contextConfig && contextConfig.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store: pick(storeConfig && storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n transformWithHostedFormData(\n values: HostedInputValues,\n data: HostedFormOrderData,\n nonce: string,\n ): PaymentRequestBody {\n const {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment = {},\n paymentMethod,\n paymentMethodMeta,\n } = data;\n const consignment = checkout && checkout.consignments[0];\n const shippingAddress = consignment && consignment.shippingAddress;\n const shippingOption = consignment && consignment.selectedShippingOption;\n\n return {\n additionalAction,\n authToken,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n customer:\n order &&\n order.billingAddress &&\n checkout &&\n mapToInternalCustomer(checkout.customer, order.billingAddress),\n billingAddress:\n order && order.billingAddress && mapToInternalAddress(order.billingAddress),\n shippingAddress:\n shippingAddress &&\n checkout &&\n mapToInternalAddress(shippingAddress, checkout.consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: this._transformHostedInputValues(values, payment, nonce),\n quoteMeta: {\n request: {\n ...paymentMethodMeta,\n geoCountryCode: config && config.context.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store:\n config &&\n pick(config.storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n private _transformPaymentMethod(paymentMethod: PaymentMethod): PaymentMethod {\n if (paymentMethod.method === 'multi-option' && !paymentMethod.gateway) {\n return { ...paymentMethod, gateway: paymentMethod.id };\n }\n\n if (paymentMethod.initializationData && paymentMethod.initializationData.gateway) {\n return { ...paymentMethod, id: paymentMethod.initializationData.gateway };\n }\n\n if (paymentMethod.id === CheckoutButtonMethodType.BRAINTREE_VENMO) {\n return { ...paymentMethod, id: CheckoutButtonMethodType.BRAINTREE_PAYPAL };\n }\n\n return paymentMethod;\n }\n\n private _transformHostedInputValues(\n values: HostedInputValues,\n payment: HostedCreditCardInstrument | HostedVaultedInstrument,\n nonce: string,\n ): PaymentInstrument {\n return 'instrumentId' in payment\n ? {\n ...payment,\n ccCvv: values.cardCodeVerification,\n ccNumber:\n values.cardNumberVerification &&\n this._cardNumberFormatter.unformat(values.cardNumberVerification),\n hostedFormNonce: nonce,\n }\n : {\n ...payment,\n ccCvv: values.cardCode,\n ccExpiry: this._cardExpiryFormatter.toObject(values.cardExpiry || ''),\n ccName: values.cardName || '',\n ccNumber: this._cardNumberFormatter.unformat(values.cardNumber || ''),\n hostedFormNonce: nonce,\n };\n }\n\n private _mapShippingAddress(\n checkoutState: InternalCheckoutSelectors,\n paymentMethod?: PaymentMethod,\n ): Address | undefined {\n if (paymentMethod) {\n const isBopisEnabled = paymentMethod.initializationData?.bopis?.enabled;\n const requiredAddress = paymentMethod.initializationData?.bopis?.requiredAddress;\n const consignments = checkoutState.consignments.getConsignments();\n const isPickup = consignments?.every((consignment) => consignment.selectedPickupOption);\n\n if (isBopisEnabled && isPickup && requiredAddress === 'none') {\n return undefined;\n }\n }\n\n return checkoutState.shippingAddress.getShippingAddress();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum PaymentProviderCustomerType {\n UpdatePaymentProviderCustomer = 'UPDATE_PAYMENT_PROVIDER_CUSTOMER',\n}\n\nexport type PaymentProviderCustomerAction = UpdatePaymentProviderCustomerAction;\n\nexport interface UpdatePaymentProviderCustomerAction extends Action {\n type: PaymentProviderCustomerType.UpdatePaymentProviderCustomer;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { Observable, of } from 'rxjs';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport {\n PaymentProviderCustomerAction,\n PaymentProviderCustomerType,\n} from './payment-provider-customer-actions';\n\nexport default class PaymentProviderCustomerActionCreator {\n updatePaymentProviderCustomer(\n providerCustomerData: PaymentProviderCustomer,\n ): Observable {\n return of(\n createAction(\n PaymentProviderCustomerType.UpdatePaymentProviderCustomer,\n providerCustomerData,\n ),\n );\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderPaymentsAction } from '../order';\n\nexport enum PaymentStrategyActionType {\n ExecuteFailed = 'PAYMENT_STRATEGY_EXECUTE_FAILED',\n ExecuteRequested = 'PAYMENT_STRATEGY_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'PAYMENT_STRATEGY_EXECUTE_SUCCEEDED',\n FinalizeFailed = 'PAYMENT_STRATEGY_FINALIZE_FAILED',\n FinalizeRequested = 'PAYMENT_STRATEGY_FINALIZE_REQUESTED',\n FinalizeSucceeded = 'PAYMENT_STRATEGY_FINALIZE_SUCCEEDED',\n InitializeFailed = 'PAYMENT_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'PAYMENT_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'PAYMENT_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type PaymentStrategyAction =\n | PaymentStrategyExecuteAction\n | PaymentStrategyFinalizeAction\n | PaymentStrategyInitializeAction\n | PaymentStrategyDeinitializeAction\n | PaymentStrategyWidgetAction;\n\nexport type PaymentStrategyExecuteAction =\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyFinalizeAction =\n | FinalizeRequestedAction\n | FinalizeSucceededAction\n | FinalizeFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type PaymentStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type PaymentStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface ExecuteRequestedAction extends Action {\n type: PaymentStrategyActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action {\n type: PaymentStrategyActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: PaymentStrategyActionType.ExecuteFailed;\n}\n\nexport interface FinalizeRequestedAction extends Action {\n type: PaymentStrategyActionType.FinalizeRequested;\n}\n\nexport interface FinalizeSucceededAction extends Action {\n type: PaymentStrategyActionType.FinalizeSucceeded;\n}\n\nexport interface FinalizeFailedAction extends Action {\n type: PaymentStrategyActionType.FinalizeFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: PaymentStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\n\nimport { PaymentRequestOptions } from './payment-request-options';\nimport { PaymentStrategyActionType, PaymentStrategyWidgetAction } from './payment-strategy-actions';\n\nexport default class PaymentStrategyWidgetActionCreator {\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n return concat(\n of(createAction(PaymentStrategyActionType.WidgetInteractionStarted, undefined, meta)),\n defer(() =>\n method().then(() =>\n createAction(\n PaymentStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.WidgetInteractionFailed, error, meta),\n ),\n );\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { AmazonPayRemoteCheckout } from './methods';\n\nexport enum RemoteCheckoutActionType {\n ForgetCheckoutRemoteCustomerRequested = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED',\n ForgetCheckoutRemoteCustomerSucceeded = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED',\n ForgetCheckoutRemoteCustomerFailed = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED',\n\n InitializeRemoteBillingRequested = 'INITIALIZE_REMOTE_BILLING_REQUESTED',\n InitializeRemoteBillingSucceeded = 'INITIALIZE_REMOTE_BILLING_SUCCEEDED',\n InitializeRemoteBillingFailed = 'INITIALIZE_REMOTE_BILLING_FAILED',\n\n InitializeRemoteShippingRequested = 'INITIALIZE_REMOTE_SHIPPING_REQUESTED',\n InitializeRemoteShippingSucceeded = 'INITIALIZE_REMOTE_SHIPPING_SUCCEEDED',\n InitializeRemoteShippingFailed = 'INITIALIZE_REMOTE_SHIPPING_FAILED',\n\n InitializeRemotePaymentRequested = 'INITIALIZE_REMOTE_PAYMENT_REQUESTED',\n InitializeRemotePaymentSucceeded = 'INITIALIZE_REMOTE_PAYMENT_SUCCEEDED',\n InitializeRemotePaymentFailed = 'INITIALIZE_REMOTE_PAYMENT_FAILED',\n\n LoadRemoteSettingsRequested = 'LOAD_REMOTE_SETTINGS_REQUESTED',\n LoadRemoteSettingsSucceeded = 'LOAD_REMOTE_SETTINGS_SUCCEEDED',\n LoadRemoteSettingsFailed = 'LOAD_REMOTE_SETTINGS_FAILED',\n\n SignOutRemoteCustomerRequested = 'SIGN_OUT_REMOTE_CUSTOMER_REQUESTED',\n SignOutRemoteCustomerSucceeded = 'SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED',\n SignOutRemoteCustomerFailed = 'SIGN_OUT_REMOTE_CUSTOMER_FAILED',\n\n UpdateRemoteCheckout = 'UPDATE_REMOTE_CHECKOUT',\n}\n\nexport type RemoteCheckoutAction =\n | ForgetCheckoutRemoteCustomerAction\n | InitializeRemoteBillingAction\n | InitializeRemoteShippingAction\n | InitializeRemotePaymentAction\n | SignOutRemoteCustomerAction\n | LoadRemoteSettingsAction\n | UpdateRemoteCheckoutAction;\n\nexport type ForgetCheckoutRemoteCustomerAction =\n | ForgetCheckoutRemoteCustomerRequestedAction\n | ForgetCheckoutRemoteCustomerSucceededAction\n | ForgetCheckoutRemoteCustomerFailedAction;\n\nexport interface ForgetCheckoutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested;\n}\n\nexport interface ForgetCheckoutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded;\n}\n\nexport interface ForgetCheckoutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed;\n}\n\nexport type InitializeRemoteBillingAction =\n | InitializeRemoteBillingSucceededAction\n | InitializeRemoteBillingFailedAction\n | InitializeRemoteBillingRequestedAction;\n\nexport interface InitializeRemoteBillingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingSucceeded;\n}\n\nexport interface InitializeRemoteBillingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingFailed;\n}\n\nexport interface InitializeRemoteBillingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingRequested;\n}\n\nexport type InitializeRemoteShippingAction =\n | InitializeRemoteShippingSucceededAction\n | InitializeRemoteShippingFailedAction\n | InitializeRemoteShippingRequestedAction;\n\nexport interface InitializeRemoteShippingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingSucceeded;\n}\n\nexport interface InitializeRemoteShippingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingFailed;\n}\n\nexport interface InitializeRemoteShippingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingRequested;\n}\n\nexport type InitializeRemotePaymentAction =\n | InitializeRemotePaymentSucceededAction\n | InitializeRemotePaymentFailedAction\n | InitializeRemotePaymentRequestedAction;\n\nexport interface InitializeRemotePaymentSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentSucceeded;\n}\n\nexport interface InitializeRemotePaymentFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentFailed;\n}\n\nexport interface InitializeRemotePaymentRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentRequested;\n}\n\nexport type SignOutRemoteCustomerAction =\n | SignOutRemoteCustomerSucceededAction\n | SignOutRemoteCustomerFailedAction\n | SignOutRemoteCustomerRequestedAction;\n\nexport interface SignOutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded;\n}\n\nexport interface SignOutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerFailed;\n}\n\nexport interface SignOutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerRequested;\n}\n\nexport type LoadRemoteSettingsAction =\n | LoadRemoteSettingsSucceededAction\n | LoadRemoteSettingsRequestedAction\n | LoadRemoteSettingsFailedAction;\n\nexport interface LoadRemoteSettingsSucceededAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsSucceeded;\n}\n\nexport interface LoadRemoteSettingsRequestedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsRequested;\n}\n\nexport interface LoadRemoteSettingsFailedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsFailed;\n}\n\nexport interface UpdateRemoteCheckoutAction extends Action {\n type: RemoteCheckoutActionType.UpdateRemoteCheckout;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutActionCreator } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutRequestSender, {\n InitializePaymentOptions,\n} from './remote-checkout-request-sender';\nimport { RemoteCheckoutStateData } from './remote-checkout-state';\n\n/**\n * @todo Convert this file into TypeScript properly\n * i.e.: Action\n */\nexport default class RemoteCheckoutActionCreator {\n constructor(\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n ) {}\n\n initializeBilling(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemoteBillingRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializeBilling(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteBillingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteBillingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializeShipping(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingRequested,\n undefined,\n { methodId },\n ),\n );\n\n this._remoteCheckoutRequestSender\n .initializeShipping(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteShippingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemotePaymentRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializePayment(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemotePaymentSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemotePaymentFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n loadSettings(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .loadSettings(methodId, options)\n .then(({ body }) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsSucceeded, body, {\n methodId,\n }),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.LoadRemoteSettingsFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n signOut(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.SignOutRemoteCustomerRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .signOut(methodId, options)\n .then(() => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n forgetCheckout(methodId: string, options?: RequestOptions): Observable {\n return concat(\n of(\n createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested,\n undefined,\n { methodId },\n ),\n ),\n defer(async () => {\n await this._remoteCheckoutRequestSender.forgetCheckout(options);\n await this._checkoutActionCreator.loadCurrentCheckout();\n\n return createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed,\n error,\n { methodId },\n ),\n ),\n );\n }\n\n updateCheckout(\n methodId: K,\n data: Partial,\n ): Action {\n return createAction(RemoteCheckoutActionType.UpdateRemoteCheckout, data, { methodId });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class RemoteCheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n initializeBilling(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/billing`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializeShipping(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/shipping`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializePayment(\n methodName: string,\n params?: InitializePaymentOptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/payment`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n loadSettings(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/settings`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n signOut(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/signout`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n generateToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/remote-checkout-token';\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n trackAuthorizationEvent({ timeout }: RequestOptions = {}): Promise> {\n const url =\n '/remote-checkout/events/shopper-checkout-service-provider-authorization-requested';\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n forgetCheckout({ timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/forget-checkout`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n\nexport interface InitializePaymentOptions {\n authorizationToken?: string;\n customerMessage?: string;\n referenceId?: string;\n useStoreCredit?: boolean;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nimport { ConsignmentMeta } from './consignment';\n\nexport enum ConsignmentActionType {\n CreateConsignmentsRequested = 'CREATE_CONSIGNMENTS_REQUESTED',\n CreateConsignmentsSucceeded = 'CREATE_CONSIGNMENTS_SUCCEEDED',\n CreateConsignmentsFailed = 'CREATE_CONSIGNMENTS_FAILED',\n\n UpdateConsignmentRequested = 'UPDATE_CONSIGNMENT_REQUESTED',\n UpdateConsignmentSucceeded = 'UPDATE_CONSIGNMENT_SUCCEEDED',\n UpdateConsignmentFailed = 'UPDATE_CONSIGNMENT_FAILED',\n\n DeleteConsignmentRequested = 'DELETE_CONSIGNMENT_REQUESTED',\n DeleteConsignmentSucceeded = 'DELETE_CONSIGNMENT_SUCCEEDED',\n DeleteConsignmentFailed = 'DELETE_CONSIGNMENT_FAILED',\n\n UpdateShippingOptionRequested = 'UPDATE_SHIPPING_OPTION_REQUESTED',\n UpdateShippingOptionSucceeded = 'UPDATE_SHIPPING_OPTION_SUCCEEDED',\n UpdateShippingOptionFailed = 'UPDATE_SHIPPING_OPTION_FAILED',\n\n LoadShippingOptionsRequested = 'LOAD_SHIPPING_OPTIONS_REQUESTED',\n LoadShippingOptionsSucceeded = 'LOAD_SHIPPING_OPTIONS_SUCCEEDED',\n LoadShippingOptionsFailed = 'LOAD_SHIPPING_OPTIONS_FAILED',\n}\n\nexport type ConsignmentAction =\n | CreateConsignmentsAction\n | UpdateConsignmentAction\n | DeleteConsignmentAction\n | UpdateShippingOptionAction\n | LoadShippingOptionsAction;\n\nexport type CreateConsignmentsAction =\n | CreateConsignmentsRequestedAction\n | CreateConsignmentsSucceededAction\n | CreateConsignmentsFailedAction;\n\nexport type UpdateConsignmentAction =\n | UpdateConsignmentRequestedAction\n | UpdateConsignmentSucceededAction\n | UpdateConsignmentFailedAction;\n\nexport type DeleteConsignmentAction =\n | DeleteConsignmentRequestedAction\n | DeleteConsignmentSucceededAction\n | DeleteConsignmentFailedAction;\n\nexport type UpdateShippingOptionAction =\n | UpdateShippingOptionRequestedAction\n | UpdateShippingOptionSucceededAction\n | UpdateShippingOptionFailedAction;\n\nexport type LoadShippingOptionsAction =\n | LoadShippingOptionsRequestedAction\n | LoadShippingOptionsSucceededAction\n | LoadShippingOptionsFailedAction;\n\nexport interface CreateConsignmentsRequestedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsRequested;\n}\n\nexport interface CreateConsignmentsSucceededAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsSucceeded;\n}\n\nexport interface CreateConsignmentsFailedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsFailed;\n}\n\nexport interface UpdateConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentRequested;\n}\n\nexport interface UpdateConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentSucceeded;\n}\n\nexport interface UpdateConsignmentFailedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentFailed;\n}\n\nexport interface DeleteConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentRequested;\n}\n\nexport interface DeleteConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentSucceeded;\n}\n\nexport interface DeleteConsignmentFailedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentFailed;\n}\n\nexport interface UpdateShippingOptionRequestedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionRequested;\n}\n\nexport interface UpdateShippingOptionSucceededAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionSucceeded;\n}\n\nexport interface UpdateShippingOptionFailedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionFailed;\n}\n\nexport interface LoadShippingOptionsRequestedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsRequested;\n}\n\nexport interface LoadShippingOptionsSucceededAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsSucceeded;\n}\n\nexport interface LoadShippingOptionsFailedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { find } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { Cart } from '../cart';\nimport {\n CheckoutIncludes,\n CheckoutParams,\n CheckoutRequestSender,\n InternalCheckoutSelectors,\n ReadableCheckoutStore,\n} from '../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport Consignment, {\n ConsignmentAssignmentBaseRequestBodyWithAddress,\n ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ConsignmentAssignmentRequestBody,\n ConsignmentCreateRequestBody,\n ConsignmentLineItem,\n ConsignmentRequestBody,\n ConsignmentShippingOptionRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n} from './consignment';\nimport {\n ConsignmentActionType,\n CreateConsignmentsAction,\n DeleteConsignmentAction,\n LoadShippingOptionsAction,\n UpdateConsignmentAction,\n UpdateShippingOptionAction,\n} from './consignment-actions';\nimport ConsignmentRequestSender from './consignment-request-sender';\n\nexport default class ConsignmentActionCreator {\n constructor(\n private _consignmentRequestSender: ConsignmentRequestSender,\n private _checkoutRequestSender: CheckoutRequestSender,\n ) {}\n\n unassignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n if (!existingConsignment) {\n throw new InvalidArgumentError('No consignment found for the specified address');\n }\n\n const lineItems = this._removeLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n );\n\n if (!lineItems.length) {\n return this.deleteConsignment(existingConsignment.id, options)(store);\n }\n\n return this.updateConsignment(\n {\n id: existingConsignment.id,\n address,\n lineItems,\n },\n options,\n )(store);\n };\n }\n\n assignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n return this._createOrUpdateConsignment(\n {\n id: existingConsignment && existingConsignment.id,\n address,\n lineItems: this._addLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n ),\n },\n options,\n )(store);\n };\n }\n\n selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const consignments = state.consignments.getConsignments();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!consignments || !consignments.length) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentUpdateBody = {\n id: consignments[0].id,\n shippingOptionId: id,\n };\n\n const consignmentMeta = {\n id: consignments[0].id,\n };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignmentUpdateBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n loadShippingOptions(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.LoadShippingOptionsRequested));\n\n this._checkoutRequestSender\n .loadCheckout(checkout.id, {\n ...options,\n params: {\n include: [CheckoutIncludes.AvailableShippingOptions],\n },\n })\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.LoadShippingOptionsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.LoadShippingOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const consignment = this._getUpdateAddressRequestBody(address, store);\n const consignments = store.getState().consignments.getConsignments();\n\n if (consignments && consignments.length) {\n (consignment as ConsignmentUpdateRequestBody).id = consignments[0].id;\n }\n\n return this._createOrUpdateConsignment(consignment, options)(store);\n };\n }\n\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.CreateConsignmentsRequested));\n\n this._consignmentRequestSender\n .createConsignments(checkout.id, consignments, options)\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.CreateConsignmentsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.CreateConsignmentsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n const consignmentMeta = { id: consignmentId };\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .deleteConsignment(checkout.id, consignmentId, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.DeleteConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n updateShippingOption(\n consignment: ConsignmentShippingOptionRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n private _createOrUpdateConsignment(\n consignment: ConsignmentCreateRequestBody | ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (this._isUpdateConsignmentRequest(consignment)) {\n return this.updateConsignment(consignment, options)(store);\n }\n\n return this.createConsignments([consignment], options)(store);\n };\n }\n\n private _getUpdateAddressRequestBody(\n address: AddressRequestBody,\n store: ReadableCheckoutStore,\n ): ConsignmentRequestBody {\n const state = store.getState();\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { physicalItems, customItems = [] } = cart.lineItems;\n\n return {\n address,\n lineItems: [...physicalItems, ...customItems].map((item) => ({\n itemId: item.id,\n quantity: item.quantity,\n })),\n };\n }\n\n private _removeLineItems(\n lineItems: ConsignmentLineItem[],\n consignment: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return this._hydrateLineItems(consignment.lineItemIds, cart)\n .map((existingItem) => {\n const sharedItem = find(\n lineItems,\n (lineItem) => lineItem.itemId === existingItem.itemId,\n );\n\n return {\n ...existingItem,\n quantity: sharedItem\n ? existingItem.quantity - sharedItem.quantity\n : existingItem.quantity,\n };\n })\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _addLineItems(\n lineItems: ConsignmentLineItem[],\n consignment?: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!consignment) {\n return lineItems;\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return lineItems\n .concat(this._hydrateLineItems(consignment.lineItemIds, cart))\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _hydrateLineItems(lineItemIds: string[], cart: Cart): ConsignmentLineItem[] {\n return lineItemIds.map((itemId) => {\n const item = find(cart.lineItems.physicalItems, (lineItem) => lineItem.id === itemId);\n\n return {\n itemId,\n quantity: item ? item.quantity : 0,\n };\n });\n }\n\n private _isUpdateConsignmentRequest(\n request: ConsignmentRequestBody,\n ): request is ConsignmentUpdateRequestBody {\n const updateRequest = request as ConsignmentUpdateRequestBody;\n\n return !!updateRequest.id;\n }\n\n private _consignmentHasAddress(\n consignment:\n | ConsignmentAssignmentBaseRequestBodyWithAddress\n | ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ): consignment is ConsignmentAssignmentBaseRequestBodyWithAddress {\n return typeof consignment === 'object' && 'address' in consignment;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutParams } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { ConsignmentsRequestBody, ConsignmentUpdateRequestBody } from './consignment';\n\nconst DEFAULT_INCLUDES = [\n 'consignments.availableShippingOptions',\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n];\n\nexport default class ConsignmentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createConsignments(\n checkoutId: string,\n consignments: ConsignmentsRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n updateConsignment(\n checkoutId: string,\n consignment: ConsignmentUpdateRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = consignment;\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n deleteConsignment(\n checkoutId: string,\n consignmentId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${consignmentId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = joinIncludes(DEFAULT_INCLUDES);\n\n return this._requestSender.delete(url, { params: { include }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Country } from '../geography';\n\nexport enum ShippingCountryActionType {\n LoadShippingCountriesRequested = 'LOAD_SHIPPING_COUNTRIES_REQUESTED',\n LoadShippingCountriesSucceeded = 'LOAD_SHIPPING_COUNTRIES_SUCCEEDED',\n LoadShippingCountriesFailed = 'LOAD_SHIPPING_COUNTRIES_FAILED',\n}\n\nexport type LoadShippingCountriesAction =\n | LoadShippingCountriesRequestedAction\n | LoadShippingCountriesSucceededAction\n | LoadShippingCountriesFailedAction;\n\nexport interface LoadShippingCountriesRequestedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesRequested;\n}\n\nexport interface LoadShippingCountriesSucceededAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesSucceeded;\n}\n\nexport interface LoadShippingCountriesFailedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport CheckoutStore from '../checkout/checkout-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryRequestSender from './shipping-country-request-sender';\n\nexport default class ShippingCountryActionCreator {\n constructor(\n private _shippingCountryRequestSender: ShippingCountryRequestSender,\n private _store: CheckoutStore,\n ) {}\n\n loadCountries(options?: RequestOptions): Observable {\n const { checkout } = this._store.getState();\n const checkoutData = checkout.getCheckout();\n\n const channelId = checkoutData ? checkoutData.channelId : null;\n\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesRequested));\n\n this._shippingCountryRequestSender\n .loadCountries(channelId, options)\n .then((response) => {\n observer.next(\n createAction(\n ShippingCountryActionType.LoadShippingCountriesSucceeded,\n response.body.data,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ShippingCountryActionType.LoadShippingCountriesFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { CountryResponseBody } from '../geography';\n\nexport default class ShippingCountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries(\n channelId: number | null,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const channelIdParam = channelId ? `?channel_id=${channelId}` : '';\n const url = `/internalapi/v1/shipping/countries${channelIdParam}`;\n\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum SpamProtectionActionType {\n InitializeFailed = 'SPAM_PROTECTION_INITIALIZE_FAILED',\n InitializeSucceeded = 'SPAM_PROTECTION_INITIALIZE_SUCCEEDED',\n InitializeRequested = 'SPAM_PROTECTION_INITIALIZE_REQUESTED',\n VerifyCheckoutRequested = 'SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED',\n VerifyCheckoutSucceeded = 'SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED',\n VerifyCheckoutFailed = 'SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED',\n ExecuteRequested = 'SPAM_PROTECTION_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'SPAM_PROTECTION_EXECUTE_SUCCEEDED',\n ExecuteFailed = 'SPAM_PROTECTION_EXECUTE_FAILED',\n}\n\nexport type SpamProtectionAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | CheckoutVerifyRequestedAction\n | CheckoutVerifyFailedAction\n | CheckoutVerifySucceededAction;\n\nexport interface InitializeRequestedAction extends Action {\n type: SpamProtectionActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: SpamProtectionActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: SpamProtectionActionType.InitializeFailed;\n}\n\nexport interface ExecuteRequestedAction extends Action {\n type: SpamProtectionActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action<{ token: string }> {\n type: SpamProtectionActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: SpamProtectionActionType.ExecuteFailed;\n}\n\nexport interface CheckoutVerifyRequestedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutRequested;\n}\n\nexport interface CheckoutVerifyFailedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutFailed;\n}\n\nexport interface CheckoutVerifySucceededAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutSucceeded;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of } from 'rxjs';\nimport { catchError, switchMap, take } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\nimport isSpamProtectionExecuteSucceededAction from './is-spam-protection-succeeded-action';\nimport { SpamProtectionAction, SpamProtectionActionType } from './spam-protection-actions';\nimport { SpamProtectionOptions } from './spam-protection-options';\nimport SpamProtectionRequestSender from './spam-protection-request-sender';\n\nexport default class SpamProtectionActionCreator {\n constructor(\n private _googleRecaptcha: GoogleRecaptcha,\n private _requestSender: SpamProtectionRequestSender,\n ) {}\n\n initialize(\n options?: SpamProtectionOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n if (!options && !document.getElementById(spamProtectionElementId)) {\n const spamProtectionElement = document.createElement('div');\n\n spamProtectionElement.setAttribute('id', spamProtectionElementId);\n document.body.appendChild(spamProtectionElement);\n }\n\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const recaptchaSitekey = storeConfig.checkoutSettings.googleRecaptchaSitekey;\n\n await this._googleRecaptcha.load(spamProtectionElementId, recaptchaSitekey);\n\n return createAction(SpamProtectionActionType.InitializeSucceeded);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.InitializeFailed, error),\n ),\n );\n }\n\n verifyCheckoutSpamProtection(): ThunkAction {\n return (store) =>\n defer(() => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return concat(\n of(createAction(SpamProtectionActionType.VerifyCheckoutRequested)),\n from(this.execute()(store)).pipe(\n switchMap((action) => {\n if (\n !isSpamProtectionExecuteSucceededAction(action) ||\n !action.payload\n ) {\n return of(action);\n }\n\n return from(\n this._requestSender.validate(checkout.id, action.payload.token),\n ).pipe(\n switchMap(({ body }) =>\n concat(\n of(action),\n of(\n createAction(\n SpamProtectionActionType.VerifyCheckoutSucceeded,\n body,\n ),\n ),\n ),\n ),\n );\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.VerifyCheckoutFailed, error),\n ),\n );\n });\n }\n\n execute(): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.ExecuteRequested)),\n this.initialize()(store),\n this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw error;\n }\n\n if (error || !token) {\n throw new SpamProtectionFailedError();\n }\n\n return createAction(SpamProtectionActionType.ExecuteSucceeded, {\n token,\n });\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.ExecuteFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class SpamProtectionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n validate(\n checkoutId: string,\n token: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/spam-protection`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: { token }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum StoreCreditActionType {\n ApplyStoreCreditRequested = 'APPLY_STORE_CREDIT_REQUESTED',\n ApplyStoreCreditSucceeded = 'APPLY_STORE_CREDIT_SUCCEEDED',\n ApplyStoreCreditFailed = 'APPLY_STORE_CREDIT_FAILED',\n}\n\nexport type StoreCreditAction = ApplyStoreCreditAction;\n\nexport type ApplyStoreCreditAction =\n | ApplyStoreCreditRequestedAction\n | ApplyStoreCreditSucceededAction\n | ApplyStoreCreditFailedAction;\n\nexport interface ApplyStoreCreditRequestedAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditRequested;\n}\n\nexport interface ApplyStoreCreditSucceededAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditSucceeded;\n}\n\nexport interface ApplyStoreCreditFailedAction\n extends Action> {\n type: StoreCreditActionType.ApplyStoreCreditFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditRequestSender from './store-credit-request-sender';\n\nexport default class StoreCreditActionCreator {\n constructor(private _storeCreditRequestSender: StoreCreditRequestSender) {}\n\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(StoreCreditActionType.ApplyStoreCreditRequested)),\n defer(async () => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(checkout.id, options)\n : this._storeCreditRequestSender.removeStoreCredit(checkout.id, options));\n\n return createAction(StoreCreditActionType.ApplyStoreCreditSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(StoreCreditActionType.ApplyStoreCreditFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class StoreCreditRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Subscriptions } from './subscriptions';\n\nexport enum SubscriptionsActionType {\n UpdateSubscriptionsRequested = 'UPDATE_SUBSCRIPTIONS_REQUESTED',\n UpdateSubscriptionsSucceeded = 'UPDATE_SUBSCRIPTIONS_SUCCEEDED',\n UpdateSubscriptionsFailed = 'UPDATE_SUBSCRIPTIONS_FAILED',\n}\nexport type UpdateSubscriptionsAction =\n | UpdateSubscriptionsRequestedAction\n | UpdateSubscriptionsSucceededAction\n | UpdateSubscriptionsFailedAction;\n\nexport interface UpdateSubscriptionsRequestedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsRequested;\n}\n\nexport interface UpdateSubscriptionsSucceededAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsSucceeded;\n}\n\nexport interface UpdateSubscriptionsFailedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsFailed;\n}\n","import { RequestError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the subscriptions fails to be updated\n */\nexport default class UpdateSubscriptionsError extends RequestError {\n constructor(response?: Response) {\n super(response);\n\n this.name = 'UpdateSubscriptionsError';\n this.type = 'update_subscriptions';\n }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n Subscriptions,\n SubscriptionsActionType,\n SubscriptionsRequestSender,\n UpdateSubscriptionsAction,\n} from '../subscription';\n\nimport { UpdateSubscriptionsError } from './errors';\n\nexport default class SubscriptionsActionCreator {\n constructor(private _subscriptionsRequestSender: SubscriptionsRequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SubscriptionsActionType.UpdateSubscriptionsRequested)),\n defer(async () => {\n const { body } = await this._subscriptionsRequestSender.updateSubscriptions(\n subscriptions,\n options,\n );\n\n return createAction(SubscriptionsActionType.UpdateSubscriptionsSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n SubscriptionsActionType.UpdateSubscriptionsFailed,\n new UpdateSubscriptionsError(error),\n ),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Subscriptions } from './subscriptions';\n\nexport default class SubscriptionsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/subscriptions';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: subscriptions, headers, timeout });\n }\n}\n","import { isPlainObject as lodashIsPlainObject } from 'lodash';\n\n// We need this wrapper because Lodash's version doesn't act as a type guard\nexport default function isPlainObject(value: any): value is object {\n return lodashIsPlainObject(value);\n}\n","import { memoize } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\n\nconst cloneDeep = memoize((input: T): T => {\n if (Array.isArray(input)) {\n // Fixed in later versions of typescript https://github.com/microsoft/TypeScript/issues/36390\n return (input as any[]).map((value: T[keyof T]) => cloneDeepSafe(value)) as any;\n }\n\n if (isPlainObject(input)) {\n return (Object.keys(input) as Array).reduce(\n (result, key) => ({\n ...result,\n [key]: cloneDeepSafe(input[key]),\n }),\n {},\n ) as T;\n }\n\n return input;\n});\n\n// Use WeakMap as the MapCache, this allows for better garbage collection\n// There's a deprecated `clear` method in the lodash implementation\n// of MapCache, hence the `any`\ncloneDeep.cache = new WeakMap() as any;\n\n/**\n * This is a wrapper function for `cloneDeep`. We need it because `cloneDeep` is\n * a memoized function using an instance of `WeakMap` as its cache. Without this\n * wrapper, the memoized function will throw an error if it is called with a\n * non-object argument.\n */\nconst cloneDeepSafe = (input: T): T => {\n return typeof input === 'object' && input !== null ? cloneDeep(input) : input;\n};\n\n/**\n * Clone the return value of a function. If the result is the same as previous\n * calls, return the previous clone instead of cloning it again.\n */\nexport default function cloneResult(fn: T): T {\n return ((...args: any[]) => cloneDeepSafe(fn(...args))) as T;\n}\n\nexport type Func = (...args: any[]) => any;\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { cloneResult as clone } from '../common/utility';\n\nexport default function createPaymentIntegrationSelectors({\n billingAddress: { getBillingAddress, getBillingAddressOrThrow },\n cart: { getCart, getCartOrThrow },\n checkout: { getCheckout, getCheckoutOrThrow, getOutstandingBalance },\n config: {\n getContextConfig,\n getHost,\n getLocale,\n getStoreConfig,\n getStoreConfigOrThrow,\n getConfig,\n },\n consignments: { getConsignments, getConsignmentsOrThrow },\n countries: { getCountries },\n customer: { getCustomer, getCustomerOrThrow },\n instruments: {\n getCardInstrument,\n getCardInstrumentOrThrow,\n getInstruments,\n getInstrumentsMeta,\n },\n order: { getOrder, getOrderOrThrow, getOrderMeta },\n payment: {\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n isPaymentDataRequired,\n },\n paymentMethods: { getPaymentMethod, getPaymentMethodOrThrow, getPaymentMethodsMeta },\n paymentProviderCustomer: { getPaymentProviderCustomer, getPaymentProviderCustomerOrThrow },\n paymentStrategies: { isInitialized: isPaymentMethodInitialized },\n shippingAddress: {\n getShippingAddress,\n getShippingAddressOrThrow,\n getShippingAddresses,\n getShippingAddressesOrThrow,\n },\n shippingCountries: { getShippingCountries },\n}: InternalCheckoutSelectors): PaymentIntegrationSelectors {\n return {\n getHost: clone(getHost),\n getLocale: clone(getLocale),\n getBillingAddress: clone(getBillingAddress),\n getBillingAddressOrThrow: clone(getBillingAddressOrThrow),\n getCart: clone(getCart),\n getCartOrThrow: clone(getCartOrThrow),\n getCheckout: clone(getCheckout),\n getCheckoutOrThrow: clone(getCheckoutOrThrow),\n getCountries: clone(getCountries),\n getStoreConfig: clone(getStoreConfig),\n getStoreConfigOrThrow: clone(getStoreConfigOrThrow),\n getConfig: clone(getConfig),\n getConsignments: clone(getConsignments),\n getConsignmentsOrThrow: clone(getConsignmentsOrThrow),\n getContextConfig: clone(getContextConfig),\n getCustomer: clone(getCustomer),\n getCustomerOrThrow: clone(getCustomerOrThrow),\n getCardInstrument: clone(getCardInstrument),\n getInstruments: clone(getInstruments),\n getCardInstrumentOrThrow: clone(getCardInstrumentOrThrow),\n getOrder: clone(getOrder),\n getOrderOrThrow: clone(getOrderOrThrow),\n getOrderMeta: clone(getOrderMeta),\n getInstrumentsMeta: clone(getInstrumentsMeta),\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n getPaymentMethod: clone(getPaymentMethod),\n getPaymentMethodOrThrow: clone(getPaymentMethodOrThrow),\n getPaymentMethodsMeta: clone(getPaymentMethodsMeta),\n getPaymentProviderCustomer: clone(getPaymentProviderCustomer),\n getPaymentProviderCustomerOrThrow: clone(getPaymentProviderCustomerOrThrow),\n getShippingAddress: clone(getShippingAddress),\n getShippingAddressOrThrow: clone(getShippingAddressOrThrow),\n getShippingAddresses: clone(getShippingAddresses),\n getShippingAddressesOrThrow: clone(getShippingAddressesOrThrow),\n getShippingCountries: clone(getShippingCountries),\n getOutstandingBalance: clone(getOutstandingBalance),\n isPaymentDataRequired,\n isPaymentMethodInitialized,\n };\n}\n","import {\n BillingAddressRequestBody,\n BuyNowCartRequestBody,\n Cart,\n HostedForm,\n HostedFormOptions,\n InitializeOffsitePaymentConfig,\n OrderRequestBody,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n RequestOptions,\n ShippingAddressRequestBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport { Checkout, CheckoutActionCreator, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { CustomerActionCreator, CustomerCredentials } from '../customer';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport {\n PaymentProviderCustomer,\n PaymentProviderCustomerActionCreator,\n} from '../payment-provider-customer';\nimport PaymentActionCreator from '../payment/payment-action-creator';\nimport PaymentMethodActionCreator from '../payment/payment-method-action-creator';\nimport PaymentStrategyWidgetActionCreator from '../payment/payment-strategy-widget-action-creator';\nimport { RemoteCheckoutActionCreator } from '../remote-checkout';\nimport { InitializePaymentOptions } from '../remote-checkout/remote-checkout-request-sender';\nimport { ConsignmentActionCreator, ShippingCountryActionCreator } from '../shipping';\nimport { PaymentHumanVerificationHandler, SpamProtectionActionCreator } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\n\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default class DefaultPaymentIntegrationService implements PaymentIntegrationService {\n private _storeProjection: DataStoreProjection;\n\n constructor(\n private _store: CheckoutStore,\n private _storeProjectionFactory: PaymentIntegrationStoreProjectionFactory,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _checkoutValidator: CheckoutValidator,\n private _hostedFormFactory: HostedFormFactory,\n private _orderActionCreator: OrderActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n private _customerActionCreator: CustomerActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _paymentStrategyWidgetActionCreator: PaymentStrategyWidgetActionCreator,\n ) {\n this._storeProjection = this._storeProjectionFactory.create(this._store);\n }\n\n createHostedForm(host: string, options: HostedFormOptions): HostedForm {\n return this._hostedFormFactory.create(host, options);\n }\n\n subscribe(\n subscriber: (state: PaymentIntegrationSelectors) => void,\n ...filters: Array<(state: PaymentIntegrationSelectors) => unknown>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n getState(): PaymentIntegrationSelectors {\n return this._storeProjection.getState();\n }\n\n async initializeOffsitePayment(\n initializeOffsitePaymentConfig: InitializeOffsitePaymentConfig,\n ): Promise {\n await this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment(initializeOffsitePaymentConfig),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadCheckout(id?: string): Promise {\n if (id) {\n await this._store.dispatch(this._checkoutActionCreator.loadCheckout(id));\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout());\n }\n\n return this._storeProjection.getState();\n }\n\n async loadDefaultCheckout(): Promise {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethod(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethods(options?: RequestOptions): Promise {\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(options));\n\n return this._storeProjection.getState();\n }\n\n async submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n return this._storeProjection.getState();\n }\n\n async submitPayment(payment: Payment): Promise {\n await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n\n return this._storeProjection.getState();\n }\n\n async finalizeOrder(options?: RequestOptions): Promise {\n const {\n order: { getOrderOrThrow },\n } = this._store.getState();\n\n await this._store.dispatch(\n this._orderActionCreator.finalizeOrder(getOrderOrThrow().orderId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async updateBillingAddress(\n payload: BillingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._billingAddressActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async updateShippingAddress(\n payload: ShippingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._consignmentActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(id, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signOutCustomer(options?: RequestOptions): Promise {\n await this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n\n return this._storeProjection.getState();\n }\n\n async createBuyNowCart(\n buyNowCartRequestBody: BuyNowCartRequestBody,\n options?: RequestOptions,\n ): Promise {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n buyNowCartRequestBody,\n options,\n );\n\n return buyNowCart;\n }\n\n async applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async verifyCheckoutSpamProtection(): Promise {\n const { checkout } = this._store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._store.dispatch(\n this._spamProtectionActionCreator.verifyCheckoutSpamProtection(),\n );\n }\n\n return this._storeProjection.getState();\n }\n\n async loadCurrentOrder(options?: RequestOptions): Promise {\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder(options));\n\n return this._storeProjection.getState();\n }\n\n async updatePaymentProviderCustomer(\n paymentProviderCustomer: PaymentProviderCustomer,\n ): Promise {\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(\n paymentProviderCustomer,\n ),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadShippingCountries(options?: RequestOptions): Promise {\n await this._store.dispatch(this._shippingCountryActionCreator.loadCountries(options));\n\n return this._storeProjection.getState();\n }\n\n async deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.deleteConsignment(consignmentId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, params, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async forgetCheckout(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.forgetCheckout(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async remoteCheckoutSignOut(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._remoteCheckoutActionCreator.signOut(methodId, options));\n\n return this._storeProjection.getState();\n }\n\n async validateCheckout(checkout?: Checkout, options?: RequestOptions): Promise {\n await this._checkoutValidator.validate(checkout, options);\n }\n\n async handlePaymentHumanVerification(\n errorOrId: Error | string,\n key?: string,\n ): Promise {\n if (typeof errorOrId === 'string') {\n return this._paymentHumanVerificationHandler.handle(errorOrId, key ?? '');\n }\n\n return this._paymentHumanVerificationHandler.handle(errorOrId);\n }\n\n async widgetInteraction(\n callback: () => Promise,\n ): Promise {\n await this._store.dispatch(\n this._paymentStrategyWidgetActionCreator.widgetInteraction(callback),\n { queueId: 'widgetInteraction' },\n );\n\n return this._storeProjection.getState();\n }\n}\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\n\nexport default class PaymentIntegrationStoreProjectionFactory {\n constructor(\n private _transformSelectors: (\n selectors: InternalCheckoutSelectors,\n ) => PaymentIntegrationSelectors,\n ) {}\n\n create(store: ReadableCheckoutStore): DataStoreProjection {\n return createDataStoreProjection(store, this._transformSelectors);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { CustomerActionCreator, CustomerRequestSender } from '../customer';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n PaymentActionCreator,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentRequestSender,\n PaymentRequestTransformer,\n} from '../payment';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\nimport PaymentStrategyWidgetActionCreator from '../payment/payment-strategy-widget-action-creator';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n} from '../shipping';\nimport {\n createSpamProtection,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentIntegrationSelectors from './create-payment-integration-selectors';\nimport DefaultPaymentIntegrationService from './default-payment-integration-service';\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default function createPaymentIntegrationService(\n store: CheckoutStore,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n const requestSender = createRequestSender({ host: getHost() });\n\n const storeProjectionFactory = new PaymentIntegrationStoreProjectionFactory(\n createPaymentIntegrationSelectors,\n );\n\n const checkoutActionCreator = new CheckoutActionCreator(\n new CheckoutRequestSender(requestSender),\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const checkoutValidator = new CheckoutValidator(new CheckoutRequestSender(requestSender));\n\n const hostedFormFactory = new HostedFormFactory(store);\n\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n new CheckoutValidator(new CheckoutRequestSender(requestSender)),\n );\n\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n\n const consignmentActionCreator = new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n );\n\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const paymentActionCreator = new PaymentActionCreator(\n new PaymentRequestSender(createPaymentClient(store)),\n orderActionCreator,\n new PaymentRequestTransformer(),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n new SpamProtectionActionCreator(\n createSpamProtection(createScriptLoader()),\n new SpamProtectionRequestSender(requestSender),\n ),\n );\n\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n\n const cartRequestSender = new CartRequestSender(requestSender);\n\n const paymentProviderCustomerActionCreator = new PaymentProviderCustomerActionCreator();\n\n const shippingCountryActionCreator = new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale: getLocale() }),\n store,\n );\n\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n new RemoteCheckoutRequestSender(requestSender),\n checkoutActionCreator,\n );\n\n const paymentStrategyWidgetActionCreator = new PaymentStrategyWidgetActionCreator();\n\n return new DefaultPaymentIntegrationService(\n store,\n storeProjectionFactory,\n checkoutActionCreator,\n checkoutValidator,\n hostedFormFactory,\n orderActionCreator,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n paymentActionCreator,\n paymentHumanVerificationHandler,\n customerActionCreator,\n cartRequestSender,\n storeCreditActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","import {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeError,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeModule,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeScriptLoader,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n PAYPAL_COMPONENTS,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaypalHostWindow } from '../paypal';\n\nexport default class BraintreeSDKCreator {\n private _client?: Promise;\n private _3ds?: Promise;\n private _paypalCheckout?: Promise;\n private _clientToken?: string;\n private _visaCheckout?: Promise;\n private _venmoCheckout?: Promise;\n private _dataCollectors: {\n default?: Promise;\n paypal?: Promise;\n } = {};\n private _window: PaypalHostWindow;\n\n constructor(private _braintreeScriptLoader: BraintreeScriptLoader) {\n this._window = window;\n }\n\n initialize(clientToken: string) {\n this._clientToken = clientToken;\n }\n\n getClient(): Promise {\n if (!this._clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this._client) {\n this._client = this._braintreeScriptLoader\n .loadClient()\n .then((client) => client.create({ authorization: this._clientToken }));\n }\n\n return this._client;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this._braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n\n if (!this._window.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(\n this._getPayPalSDKConfig(config),\n paypalSdkLoadCallback,\n );\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this._paypalCheckout = paypalCheckout.create(paypalCheckoutConfig, paypalCheckoutCallback);\n\n return this._paypalCheckout;\n }\n\n async getVenmoCheckout(\n onSuccess: (braintreeVenmoCheckout: BraintreeVenmoCheckout) => void,\n onError: (error: BraintreeError | UnsupportedBrowserError) => void,\n ): Promise {\n if (!this._venmoCheckout) {\n const client = await this.getClient();\n\n const venmoCheckout = await this._braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const venmoCheckoutCallback = (\n error: BraintreeError,\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n ): void => {\n if (error) {\n return onError(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return onError(new UnsupportedBrowserError());\n }\n\n onSuccess(braintreeVenmoCheckout);\n };\n\n this._venmoCheckout = venmoCheckout.create(venmoCheckoutConfig, venmoCheckoutCallback);\n }\n\n return this._venmoCheckout;\n }\n\n get3DS(): Promise {\n if (!this._3ds) {\n this._3ds = Promise.all([this.getClient(), this._braintreeScriptLoader.load3DS()]).then(\n ([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }),\n );\n }\n\n return this._3ds;\n }\n\n getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options && options.paypal ? 'paypal' : 'default';\n let cached = this._dataCollectors[cacheKey];\n\n if (!cached) {\n cached = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadDataCollector(),\n ])\n .then(([client, dataCollector]) =>\n dataCollector.create({ client, kount: true, ...options }),\n )\n .catch((error) => {\n if (error && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n return { deviceData: undefined, teardown: () => Promise.resolve() };\n }\n\n throw error;\n });\n\n this._dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getVisaCheckout(): Promise {\n if (!this._visaCheckout) {\n this._visaCheckout = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, visaCheckout]) => visaCheckout.create({ client }));\n }\n\n return this._visaCheckout;\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const [client, hostedFields] = await Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadHostedFields(),\n ]);\n\n return hostedFields.create({ ...options, client });\n }\n\n teardown(): Promise {\n return Promise.all([\n this._teardown(this._3ds),\n this._teardown(this._dataCollectors.default),\n this._teardown(this._dataCollectors.paypal),\n this._teardown(this._paypalCheckout),\n this._teardown(this._venmoCheckout),\n this._teardown(this._visaCheckout),\n ]).then(() => {\n this._3ds = undefined;\n this._dataCollectors = {};\n this._paypalCheckout = undefined;\n this._venmoCheckout = undefined;\n this._visaCheckout = undefined;\n });\n }\n\n private _teardown(module?: Promise) {\n return module\n ? module\n .then((mod) => mod.teardown())\n .catch((error) => {\n if (error.code !== 'METHOD_CALLED_AFTER_TEARDOWN') {\n throw error;\n }\n })\n : Promise.resolve();\n }\n\n private _getPayPalSDKConfig(config: Partial) {\n return {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n commit: false,\n };\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { Address, LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nimport { BraintreeDataCollector } from './braintree';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport {\n VisaCheckoutAddress,\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\nexport default class BraintreeVisaCheckoutPaymentProcessor {\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(\n clientToken: string,\n options: VisaCheckoutInitializeOptions,\n ): Promise {\n this._braintreeSDKCreator.initialize(clientToken);\n\n return this._braintreeSDKCreator.getVisaCheckout().then((visaCheckout) =>\n visaCheckout.createInitOptions({\n settings: {\n locale: options.locale,\n shipping: {\n collectShipping: options.collectShipping,\n },\n },\n paymentRequest: {\n currencyCode: options.currencyCode,\n subtotal: String(options.subtotal),\n },\n }),\n );\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n handleSuccess(\n payment: VisaCheckoutPaymentSuccessPayload,\n shipping?: Address,\n billing?: Address,\n ): Promise {\n return this._braintreeSDKCreator.getVisaCheckout().then((braintreeVisaCheckout) =>\n Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this._braintreeSDKCreator.getDataCollector(),\n ]).then(([tokenizedPayload, dataCollector]) => {\n const {\n shippingAddress = this._toVisaCheckoutAddress(shipping),\n billingAddress = this._toVisaCheckoutAddress(billing),\n } = tokenizedPayload;\n\n return this._postForm(\n {\n ...tokenizedPayload,\n shippingAddress,\n billingAddress,\n },\n dataCollector,\n );\n }),\n );\n }\n\n private _postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: this._getCardInformation(cardInformation),\n billing_address: this._getAddress(userEmail, billingAddress),\n shipping_address: this._getAddress(userEmail, shippingAddress),\n },\n });\n }\n\n private _toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private _getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastTwo: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n };\n }\n}\n\nexport interface VisaCheckoutInitializeOptions {\n locale?: string;\n collectShipping?: boolean;\n subtotal?: number;\n currencyCode?: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\n\nexport default function createBraintreeVisaCheckoutPaymentProcessor(\n scriptLoader: ScriptLoader,\n requestSender: RequestSender,\n) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, window);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n\n return new BraintreeVisaCheckoutPaymentProcessor(braintreeSDKCreator, requestSender);\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { VisaCheckoutHostWindow, VisaCheckoutSDK } from './visacheckout';\n\nexport default class VisaCheckoutScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: VisaCheckoutHostWindow = window,\n ) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n )\n .then(() => {\n if (!this._window.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.V;\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Masterpass, MasterpassHostWindow } from './masterpass';\n\ninterface MasterpassScriptLoaderParams {\n useMasterpassSrc: boolean;\n language: string;\n testMode?: boolean;\n checkoutId?: string;\n}\n\nexport default class MasterpassScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n public _window: MasterpassHostWindow = window,\n ) {}\n\n async load({\n useMasterpassSrc,\n language,\n testMode,\n checkoutId,\n }: MasterpassScriptLoaderParams): Promise {\n if (useMasterpassSrc) {\n const subdomain = testMode ? 'sandbox.' : '';\n const params = [`locale=${language}`, `checkoutid=${checkoutId}`];\n\n const sourceUrl = [\n `https://${subdomain}src.mastercard.com/srci/integration/merchant.js`,\n params.join('&'),\n ].join('?');\n\n await this._scriptLoader.loadScript(sourceUrl);\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n\n await this._scriptLoader.loadScript(\n `//${testMode ? 'sandbox.' : ''}masterpass.com/integration/merchant.js`,\n );\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutScriptLoader,\n} from '../../../payment/strategies/braintree';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategyActionCreator from '../../customer-strategy-action-creator';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _buttonClassName = 'visa-checkout-wrapper';\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this._paymentMethod;\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { container, onError = () => {} } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: true,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n clientToken,\n initOptions,\n ),\n ])\n .then(([visaCheckout, initOptions]) => {\n const signInButton = this._createSignInButton(\n container,\n this._buttonClassName,\n );\n\n visaCheckout.init(initOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload).catch(\n (error) => onError(error),\n ),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n\n return signInButton;\n })\n .then((signInButton) => {\n signInButton.style.visibility = 'visible';\n });\n })\n .then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut('braintreevisacheckout', options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._customerStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(async () => {\n await this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n );\n this._onPaymentSelectComplete();\n });\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _onPaymentSelectComplete(): void {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n }\n\n private _createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return (\n (container.querySelector(`.${buttonClass}`) as HTMLElement) ||\n this._insertVisaCheckoutButton(container, buttonClass)\n );\n }\n\n private _insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class DefaultCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _customerActionCreator: CustomerActionCreator,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","export default function getCallbackUrl(origin: string): string {\n return `${window.location.origin}/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=${origin}`;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n es: ['es_es', 'es_mx', 'es_pe', 'es_co', 'es_ar', 'es_cl'],\n en: [\n 'en_us',\n 'en_gb',\n 'en_ca',\n 'en_es',\n 'en_fr',\n 'en_ie',\n 'en_sg',\n 'en_au',\n 'en_nz',\n 'en_my',\n 'en_hk',\n 'en_th',\n 'en_ae',\n 'en_sa',\n 'en_qa',\n 'en_kw',\n 'en_za',\n ],\n pt: ['pt_br'],\n zu: ['zu_za'],\n ar: ['ar_sa', 'ar_ae', 'ar_qa', 'ar_kw'],\n zh: ['zh_sg', 'zh_hk'],\n ms: ['ms_my'],\n uk: ['uk_ua'],\n sv: ['sv_se'],\n hr: ['hr_hr'],\n pl: ['pl_pl'],\n nl: ['nl_be'],\n it: ['it_it'],\n de: ['de_de'],\n fr: ['fr_fr', 'fr_ca'],\n};\n","import { supportedLocales } from './masterpass-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace('-', '_').toLowerCase().split('_');\n const formattedLocale = `${language}_${country}`;\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'en_us';\n }\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n formatLocale,\n getCallbackUrl,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class MasterpassCustomerStrategy implements CustomerStrategy {\n private _signInButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { masterpass: masterpassOptions, methodId } = options;\n\n if (!masterpassOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.masterpass\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { container } = masterpassOptions;\n\n const payload = {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: cart.cartAmount.toString(),\n currency: cart.currency.code,\n cartId: cart.id,\n suppressShippingAddress: false,\n callbackUrl: getCallbackUrl('checkout'),\n };\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((Masterpass) => {\n this._signInButton = this._createSignInButton(container);\n\n this._signInButton.addEventListener('click', () => {\n Masterpass.checkout(payload);\n });\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (this._paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = this._paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = this._paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n container.appendChild(button);\n\n return button;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotImplementedError } from '../../../common/error/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class SquareCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n ) {}\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Extension } from './extension';\n\nexport enum ExtensionActionType {\n LoadExtensionsRequested = 'LOAD_EXTENSIONS_REQUESTED',\n LoadExtensionsSucceeded = 'LOAD_EXTENSIONS_SUCCEEDED',\n LoadExtensionsFailed = 'LOAD_EXTENSIONS_FAILED',\n RenderExtensionRequested = 'RENDER_EXTENSION_REQUESTED',\n RenderExtensionSucceeded = 'RENDER_EXTENSION_SUCCEEDED',\n RenderExtensionFailed = 'RENDER_EXTENSION_FAILED',\n}\n\nexport type ExtensionAction =\n | LoadExtensionsRequestedAction\n | LoadExtensionsSucceededAction\n | LoadExtensionsFailedAction\n | RenderExtensionRequestedAction\n | RenderExtensionSucceededAction\n | RenderExtensionFailedAction;\n\nexport interface LoadExtensionsRequestedAction extends Action {\n type: ExtensionActionType.LoadExtensionsRequested;\n}\n\nexport interface LoadExtensionsSucceededAction extends Action {\n type: ExtensionActionType.LoadExtensionsSucceeded;\n}\n\nexport interface LoadExtensionsFailedAction extends Action {\n type: ExtensionActionType.LoadExtensionsFailed;\n}\n\nexport interface RenderExtensionRequestedAction extends Action {\n type: ExtensionActionType.RenderExtensionRequested;\n}\n\nexport interface RenderExtensionSucceededAction extends Action {\n type: ExtensionActionType.RenderExtensionSucceeded;\n}\n\nexport interface RenderExtensionFailedAction extends Action {\n type: ExtensionActionType.RenderExtensionFailed;\n}\n","export enum ExtensionInternalEventType {\n ExtensionReady = 'EXTENSION:READY',\n ExtensionFailed = 'EXTENSION:FAILED',\n}\n\nexport interface ExtensionReadyEvent {\n type: ExtensionInternalEventType.ExtensionReady;\n}\n\nexport interface ExtensionFailedEvent {\n type: ExtensionInternalEventType.ExtensionFailed;\n}\n\nexport type ExtensionInternalEvent = ExtensionReadyEvent | ExtensionFailedEvent;\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotFoundError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to no extension configured for this region.');\n\n this.name = 'ExtensionNotFoundError';\n this.type = 'extension_not_found';\n }\n}\n","import { IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { Extension } from './extension';\n\nexport function createExtensionEventPoster(extension: Extension): IframeEventPoster {\n const iframe = document\n .querySelector(`[data-extension-id=\"${extension.id}\"]`)\n ?.querySelector('iframe');\n\n if (!iframe?.contentWindow) {\n throw new ExtensionNotFoundError(\n `Unable to post due to no extension rendered for ID: ${extension.id}.`,\n );\n }\n\n return new IframeEventPoster(extension.url, iframe.contentWindow);\n}\n","import { IFrameComponent, IFrameOptions } from 'iframe-resizer';\n\nexport {\n HeightCalculationMethod,\n IFrameComponent,\n IFrameMessageData,\n IFrameObject,\n IFrameOptions,\n IFramePage,\n IFramePageOptions,\n IFrameResizedData,\n IFrameScrollData,\n PageInfo,\n WidthCalculationMethod,\n} from 'iframe-resizer';\n\n// The reason why we are wrapping the original `iframeResizer` function imported\n// from the package is because the package sets up event listeners (window\n// resize etc...) as soon as the package is imported. Therefore, to defer the\n// side effect from happening until the function is actually being used, we are\n// importing the package inside this function. To minimise the chance of\n// importing the original package inadvertently, we are also re-exporting all of\n// its public interfaces. The re-exports do not cause any side effect because\n// they are plain TypeScript interfaces; meaning they are only used for type\n// checks rather than for code output.\nexport function iframeResizer(\n options: IFrameOptions,\n target: string | HTMLElement,\n): IFrameComponent[] {\n /* eslint-disable @typescript-eslint/no-var-requires */\n const { iframeResizer: originalIframeResizer } = require('iframe-resizer');\n\n return originalIframeResizer(options, target);\n}\n\n// We also need to wrap the original `iframeResizer.contentWindow` because\n// similarly the package sets up event listeners as soon as the package gets\n// imported. Another reason is that if it is imported at the top level using a\n// regular import statement, it will be stripped out by Webpack as it is\n// considered as \"unused\", unless we explicitly mark it as a package that\n// produces side effects.\nexport function setupContentWindowForIframeResizer(): void {\n require('iframe-resizer/js/iframeResizer.contentWindow');\n}\n","import { ExtensionEventType } from './extension-events';\n\nexport enum ExtensionInternalCommandType {\n Subscribe = 'EXTENSION_INTERNAL:SUBSCRIBE',\n Unsubscribe = 'EXTENSION_INTERNAL:UNSUBSCRIBE',\n ResizeIframe = 'EXTENSION_INTERNAL:RESIZE_IFRAME',\n}\n\nexport interface ExtensionSubscribeCommand {\n type: ExtensionInternalCommandType.Subscribe;\n payload: {\n extensionId: string;\n eventType: ExtensionEventType;\n };\n}\n\nexport interface ExtensionUnsubscribeCommand {\n type: ExtensionInternalCommandType.Unsubscribe;\n payload: {\n extensionId: string;\n eventType: ExtensionEventType;\n };\n}\n\nexport interface ExtensionResizeIframeCommand {\n type: ExtensionInternalCommandType.ResizeIframe;\n payload: {\n extensionId: string;\n };\n}\n\nexport interface ExtensionInternalCommandMap {\n [ExtensionInternalCommandType.Subscribe]: ExtensionSubscribeCommand;\n [ExtensionInternalCommandType.Unsubscribe]: ExtensionUnsubscribeCommand;\n [ExtensionInternalCommandType.ResizeIframe]: ExtensionResizeIframeCommand;\n}\n\nexport type ExtensionInternalCommand =\n | ExtensionSubscribeCommand\n | ExtensionUnsubscribeCommand\n | ExtensionResizeIframeCommand;\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotLoadedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to load an extension');\n\n this.name = 'ExtensionNotLoadedError';\n this.type = 'extension_not_loaded';\n }\n}\n","import { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { parseUrl } from '../common/url';\n\nimport { ExtensionNotLoadedError } from './errors';\nimport { ExtensionInternalCommandType } from './extension-internal-commands';\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(\n src: string,\n containerId: string,\n initCallback: () => void,\n failedCallback: () => void,\n ): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new ExtensionNotLoadedError(\n 'Unable to embed the iframe because the container element could not be found.',\n );\n }\n\n const iframe = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout, initCallback, failedCallback).catch(\n (error) => {\n container.removeChild(iframe);\n\n throw error;\n },\n );\n }\n\n private async _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n initCallback: () => void,\n failedCallback: () => void,\n ): Promise {\n const detachmentObserver = new DetachmentObserver(new MutationObserverFactory());\n\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n const promise = new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n try {\n failedCallback();\n } catch (error) {\n if (error instanceof Error) {\n // eslint-disable-next-line no-console\n console.error(\n `Extension rendering timed out after ${timeoutInterval}ms, and the callback function could not be executed. Error: ${error.message}`,\n );\n }\n }\n\n reject(\n new ExtensionNotLoadedError(\n 'Unable to load the extension because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== parseUrl(iframe.src).origin) {\n return;\n }\n\n if (isIframeEvent(event.data, ExtensionInternalCommandType.ResizeIframe)) {\n iframe.style.display = '';\n\n const iframes = iframeResizer(\n {\n autoResize: false,\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: 'bodyOffset',\n initCallback,\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n\n return detachmentObserver.ensurePresence([iframe], promise);\n }\n}\n","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n}\n\nexport interface ExtensionCommandContext {\n extensionId: string;\n}\n\nexport interface ReloadCheckoutCommand {\n type: ExtensionCommandType.ReloadCheckout;\n}\n\nexport interface ShowLoadingIndicatorCommand {\n type: ExtensionCommandType.ShowLoadingIndicator;\n payload: {\n show: boolean;\n };\n}\n\nexport interface SetIframeStyleCommand {\n type: ExtensionCommandType.SetIframeStyle;\n payload: {\n style: {\n [key: string]: string | number | null;\n };\n };\n}\n\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n}\n","import { createExtensionEventPoster } from './create-extension-event-poster';\nimport { Extension, ExtensionIframeConfig } from './extension';\nimport { ExtensionInternalEvent, ExtensionInternalEventType } from './extension-internal-events';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport class ExtensionIframe {\n private _iframe: HTMLIFrameElement | undefined;\n private _url: URL;\n\n constructor(\n private _containerId: string,\n private _extension: Extension,\n private _config: ExtensionIframeConfig,\n ) {\n const { cartId, parentOrigin } = this._config;\n\n this._url = new URL(this._extension.url);\n\n this._url.searchParams.set('extensionId', this._extension.id);\n this._url.searchParams.set('cartId', cartId);\n this._url.searchParams.set('parentOrigin', parentOrigin);\n }\n\n async attach(): Promise {\n if (\n document\n .querySelector(`[data-extension-id=\"${this._extension.id}\"]`)\n ?.querySelector('iframe')\n ) {\n return;\n }\n\n const iframeCreator = new ResizableIframeCreator();\n const iframeResizerCallback = (type: ExtensionInternalEventType) => {\n const poster = createExtensionEventPoster(this._extension);\n\n poster.post({\n type,\n });\n };\n const initCallback = () => {\n iframeResizerCallback(ExtensionInternalEventType.ExtensionReady);\n };\n const failedCallback = () => {\n iframeResizerCallback(ExtensionInternalEventType.ExtensionFailed);\n };\n\n this._iframe = await iframeCreator.createFrame(\n this._url.toString(),\n this._containerId,\n initCallback,\n failedCallback,\n );\n\n const container = document.getElementById(this._containerId);\n\n container?.setAttribute('data-extension-id', this._extension.id);\n }\n\n detach(): void {\n if (this._iframe && this._iframe.parentElement) {\n this._iframe.parentElement.removeChild(this._iframe);\n }\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { RequestOptions } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\n\nexport class ExtensionActionCreator {\n constructor(private _requestSender: ExtensionRequestSender) {}\n\n loadExtensions(\n options?: RequestOptions,\n ): ThunkAction {\n return () =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(ExtensionActionType.LoadExtensionsRequested));\n\n this._requestSender\n .loadExtensions(options)\n .then((response) => {\n const extensions = response.body;\n\n observer.next(\n createAction(ExtensionActionType.LoadExtensionsSucceeded, extensions),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(ExtensionActionType.LoadExtensionsFailed, response),\n );\n });\n });\n }\n\n renderExtension(\n container: string,\n region: ExtensionRegion,\n ): ThunkAction {\n return (store) =>\n Observable.create(async (observer: Observer) => {\n const state = store.getState();\n const { id: cartId } = state.cart.getCartOrThrow();\n const {\n links: { checkoutLink },\n checkoutSettings: { features },\n } = state.config.getStoreConfigOrThrow();\n\n if (!features['PROJECT-5029.checkout_extension']) {\n return observer.complete();\n }\n\n const extension = state.extensions.getExtensionByRegion(region);\n\n try {\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension configured for the region: ${region}.`,\n );\n }\n\n observer.next(createAction(ExtensionActionType.RenderExtensionRequested));\n\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n\n observer.next(createAction(ExtensionActionType.RenderExtensionSucceeded));\n observer.complete();\n } catch (error) {\n observer.error(\n createErrorAction(ExtensionActionType.RenderExtensionFailed, error),\n );\n }\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Extension } from './extension';\n\nexport const EXTENSIONS_API_URL = '/api/storefront/checkout-extensions';\n\nexport class ExtensionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadExtensions({ timeout, params }: RequestOptions = {}): Promise> {\n return this._requestSender.get(EXTENSIONS_API_URL, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionCommandError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension command.');\n\n this.name = 'UnsupportedExtensionCommandError';\n this.type = 'unsupported_extension_command_error';\n }\n}\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport { ExtensionNotFoundError } from './errors';\nimport { UnsupportedExtensionCommandError } from './errors/unsupported-extension-command-error';\nimport { Extension } from './extension';\nimport {\n ExtensionCommandContext,\n ExtensionCommandMap,\n ExtensionCommandType,\n} from './extension-commands';\nimport { ExtensionEvent } from './extension-events';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _listeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n listen(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandContext,\n ) => void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (!this._listeners[extensionId]) {\n this._listeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._listeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandContext,\n ) => {\n if (context?.extensionId === extensionId) {\n commandHandler(command, context);\n }\n };\n\n listener.addListener(validCommandType, commandHandlerProxy);\n\n return () => {\n listener.removeListener(validCommandType, commandHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (!this._listeners[extensionId]) {\n return;\n }\n\n const listener = this._listeners[extensionId];\n\n listener.stopListen();\n }\n\n post(extensionId: string, event: ExtensionEvent): void {\n if (!this._posters[extensionId]) {\n const extension = this._getExtensionById(extensionId);\n\n this._posters[extensionId] = createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(event);\n }\n\n private _getExtensionById(extensionId: string): Extension {\n const {\n extensions: { getExtensions },\n } = this._store.getState();\n\n this._extensions = getExtensions();\n\n if (!this._extensions) {\n throw new ExtensionNotFoundError(`Extension configurations not found.`);\n }\n\n const extension = this._extensions.find((e) => e.id === extensionId);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for ID: ${extensionId}.`,\n );\n }\n\n return extension;\n }\n\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n}\n","import { Consignment } from '../shipping';\n\nexport enum ExtensionEventType {\n ConsignmentsChanged = 'EXTENSION:CONSIGNMENTS_CHANGED',\n}\n\nexport interface ConsignmentsChangedEvent {\n type: ExtensionEventType.ConsignmentsChanged;\n payload: {\n consignments: Consignment[];\n previousConsignments: Consignment[];\n };\n}\n\nexport type ExtensionEvent = ConsignmentsChangedEvent;\n\nexport interface ExtensionEventMap {\n [ExtensionEventType.ConsignmentsChanged]: ConsignmentsChangedEvent;\n}\n","import { CheckoutSelectors } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { IframeEventListener } from '../common/iframe';\n\nimport { ExtensionEvent, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommandMap,\n ExtensionInternalCommandType,\n ExtensionSubscribeCommand,\n ExtensionUnsubscribeCommand,\n} from './extension-internal-commands';\nimport { ExtensionMessenger } from './extension-messenger';\nimport { ExtensionChangeSubscriber, ExtensionChangeUnsubscriber } from './subscribers';\n\nexport class ExtensionEventBroadcaster {\n private _subscribed: { [id: string]: boolean } = {};\n private _unsubscribers: { [type: string]: ExtensionChangeUnsubscriber } = {};\n private _listeners: { [id: string]: IframeEventListener } = {};\n\n constructor(\n private _store: DataStoreProjection,\n private _extensionMessenger: ExtensionMessenger,\n private _subscribers: Record,\n ) {}\n\n listen(): void {\n const {\n data: { getExtensions },\n } = this._store.getState();\n\n getExtensions()?.forEach((extension) => {\n if (this._listeners[extension.id]) {\n return;\n }\n\n const eventListener = new IframeEventListener(\n extension.url,\n );\n\n eventListener.addListener(\n ExtensionInternalCommandType.Subscribe,\n this._handleSubscribe.bind(this),\n );\n\n eventListener.addListener(\n ExtensionInternalCommandType.Unsubscribe,\n this._handleUnsubscribe.bind(this),\n );\n\n eventListener.listen();\n\n this._listeners[extension.id] = eventListener;\n });\n }\n\n broadcast(event: ExtensionEvent): void {\n const {\n data: { getExtensions },\n } = this._store.getState();\n\n getExtensions()?.forEach((extension) => {\n if (!this._subscribed[extension.id]) {\n return;\n }\n\n this._extensionMessenger.post(extension.id, event);\n });\n }\n\n private _handleSubscribe({\n payload: { eventType, extensionId },\n }: ExtensionSubscribeCommand): void {\n this._subscribed[extensionId] = true;\n\n if (this._unsubscribers[eventType]) {\n return;\n }\n\n this._unsubscribers[eventType] = this._subscribers[eventType](this._store, this);\n }\n\n private _handleUnsubscribe({\n payload: { eventType, extensionId },\n }: ExtensionUnsubscribeCommand): void {\n delete this._subscribed[extensionId];\n\n if (Object.keys(this._subscribed).length) {\n return;\n }\n\n this._unsubscribers[eventType]?.();\n\n delete this._unsubscribers[eventType];\n }\n}\n","import { CheckoutSelectors } from '../../checkout';\nimport { DataStoreProjection } from '../../common/data-store';\nimport { ExtensionEventBroadcaster } from '../extension-event-broadcaster';\nimport { ExtensionEventType } from '../extension-events';\n\nimport { ExtensionChangeSubscriber } from './extension-change-subscriber';\n\nexport const subscribeConsignmentsChange: ExtensionChangeSubscriber = (\n store: DataStoreProjection,\n broadcaster: ExtensionEventBroadcaster,\n) => {\n const {\n data: { getConsignments: getInitialConsignments },\n } = store.getState();\n\n let consignments = getInitialConsignments() ?? [];\n\n return store.subscribe(\n ({ data: { getConsignments } }) => {\n const currentConsignments = getConsignments() ?? [];\n\n if (currentConsignments === consignments) {\n return;\n }\n\n broadcaster.broadcast({\n type: ExtensionEventType.ConsignmentsChanged,\n payload: {\n consignments: currentConsignments,\n previousConsignments: consignments,\n },\n });\n\n consignments = currentConsignments;\n },\n ({ data: { getConsignments } }) => getConsignments(),\n );\n};\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenV2HostWindow } from '../types';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenV2HostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA',\n crossorigin: 'anonymous',\n },\n },\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","export enum AdyenV3ActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2 = 'threeDS2',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n\n /*\n * The Component displays the widget which the shopper uses to complete the payment.\n * */\n Sdk = 'sdk',\n}\n\nexport enum AdyenV2ActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2Challenge = 'threeDS2Challenge',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface BoletoDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n shopperName?: {\n firstName?: string;\n lastName?: string;\n };\n socialSecurityNumber?: string;\n}\n\ninterface CardPaymentMethodState extends AdyenPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenV2Action {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenV2ActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenV3Action {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenV3ActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport type AdyenAction = AdyenV2Action | AdyenV3Action;\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n\n /**\n * A callback that gets called when an action, for example a QR code or 3D Secure 2 authentication screen, is shown to the shopper\n */\n onActionHandled?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n\n showBrandsUnderCardNumber?: boolean;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenComponentEventState, component: AdyenComponent): void;\n\n /**\n * Called when the shopper selects the Pay button and payment details are valid.\n */\n onSubmit?(state: AdyenComponentEventState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenV2Action | AdyenV3Action,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | AdyenV3ThreeDS2ChallengeComponentOptions\n | AdyenV2ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: AdyenComponentState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n submit(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * Configuration for specific payment methods.\n */\n paymentMethodsConfiguration?: {\n klarna: {\n useKlarnaWidget: boolean;\n };\n klarna_account: {\n useKlarnaWidget: boolean;\n };\n klarna_paynow: {\n useKlarnaWidget: boolean;\n };\n card?: {\n installmentOptions?: {\n card?: {\n values: number[];\n plans?: string[];\n };\n visa?: {\n values: number[];\n plans?: string[];\n };\n mc?: {\n values: number[];\n plans?: string[];\n };\n diners?: {\n values: number[];\n plans?: string[];\n };\n jcb?: {\n values: number[];\n plans?: string[];\n };\n showInstallmentAmounts?: boolean;\n };\n };\n };\n\n showPayButton?: boolean;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: AdyenComponentEventState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: AdyenComponentEventState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n firstName?: string;\n lastName?: string;\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenCreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\ntype AdyenClientConstructor = (configuration: AdyenConfiguration) => Promise;\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\nexport interface AdyenV3HostWindow extends Window {\n AdyenCheckout?: AdyenClientConstructor;\n}\n\nexport interface AdyenV2HostWindow extends Window {\n AdyenCheckout?: new (configuration: AdyenConfiguration) => AdyenClient;\n}\n\nexport interface AdyenIdealComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface AdyenThreeDS2Options extends AdyenAdditionalActionCallbacks {\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVV2/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface IdealStateData {\n issuer: string;\n}\n\ninterface SepaStateData {\n ownerName: string;\n ibanNumber: string;\n}\n\ninterface CardStateData {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenComponentState {\n data?: CardStateData | IdealStateData | SepaStateData;\n issuer?: string;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n installments?: { value: number; plan?: 'string' };\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface BoletoState {\n data: BoletoDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface AdyenV3ThreeDS2ChallengeComponentOptions {\n challengeWindowSize?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenV2ThreeDS2ChallengeComponentOptions {\n size?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ActionHandledReturnObject {\n componentType: string;\n actionDescription: string;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenValidationState {\n valid: boolean;\n fieldType?: AdyenCardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenCardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenComponentEventState = CardState | BoletoState | WechatState;\n\nexport type AdyenComponentOptions =\n | AdyenCreditCardComponentOptions\n | AdyenIdealComponentOptions\n | AdyenBoletoComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport interface AdyenV3PaymentMethodInitializationData {\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n installmentOptions?: null | {\n card?: {\n values: number[];\n plans?: string[];\n };\n visa?: {\n values: number[];\n plans?: string[];\n };\n mc?: {\n values: number[];\n plans?: string[];\n };\n diners?: {\n values: number[];\n plans?: string[];\n };\n jcb?: {\n values: number[];\n plans?: string[];\n };\n };\n}\n\nexport interface AdyenV2PaymentMethodInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { AdyenComponentEventState, CardState } from '../types';\n\nexport default function isCardState(param: AdyenComponentEventState): param is CardState {\n return (\n (typeof param === 'object' &&\n typeof (param as CardState).data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof (param as CardState).data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrumentPayload,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import StandardError from './standard-error';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { some } from 'lodash';\n\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentEventState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV2ActionType,\n AdyenV2PaymentInitializeOptions,\n AdyenV2PaymentMethodInitializationData,\n AdyenV2ScriptLoader,\n CardStateErrors,\n isAccountState,\n isCardState,\n WithAdyenV2PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n BillingAddress,\n getBrowserInfo,\n HostedInstrument,\n InvalidArgumentError,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class AdyenV2PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentEventState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV2PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV2PaymentInitializeOptions,\n ): Promise {\n const { adyenv2 } = options;\n\n if (!adyenv2) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv2\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv2;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { originKey, clientKey, environment, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = clientKey || '';\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n const shouldSaveInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument;\n\n if (!payment) {\n return Promise.reject(new PaymentArgumentInvalidError(['payment']));\n }\n\n this._validateCardData();\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState;\n\n if (!componentState) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n if (isCardState(componentState) || isAccountState(componentState)) {\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument:\n shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV2PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv2\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _getThreeDS2ChallengeWidgetSize(): string {\n const { additionalActionOptions, threeDS2Options } = this._getPaymentInitializeOptions();\n const widgetSize = additionalActionOptions.widgetSize || threeDS2Options?.widgetSize;\n\n if (!widgetSize) {\n return '05';\n }\n\n return widgetSize;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { threeDS2ContainerId, additionalActionOptions } =\n this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete } = additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n size: this._getThreeDS2ChallengeWidgetSize(),\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenV2ActionType.ThreeDS2Challenge ||\n adyenAction.type === AdyenV2ActionType.QRCode,\n );\n }\n\n additionalActionComponent.mount(`#${containerId || threeDS2ContainerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv2.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv2.options,\n styles: {\n ...adyenv2.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv2.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv2.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv2.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv2.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n switch (paymentMethod.method) {\n case AdyenPaymentMethodType.CreditCard:\n case AdyenPaymentMethodType.ACH:\n case AdyenPaymentMethodType.Bancontact: {\n const billingAddress = this._paymentIntegrationService\n .getState()\n .getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) => this._updateComponentState(componentState),\n data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n break;\n }\n\n case AdyenPaymentMethodType.IDEAL:\n case AdyenPaymentMethodType.SEPA:\n if (!adyenv2.hasVaultedInstruments) {\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) =>\n this._updateComponentState(componentState),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n ),\n );\n }\n } else {\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n break;\n\n case AdyenPaymentMethodType.AliPay:\n case AdyenPaymentMethodType.GiroPay:\n case AdyenPaymentMethodType.Sofort:\n case AdyenPaymentMethodType.Klarna:\n case AdyenPaymentMethodType.KlarnaPayNow:\n case AdyenPaymentMethodType.KlarnaAccount:\n case AdyenPaymentMethodType.Vipps:\n case AdyenPaymentMethodType.WeChatPayQR:\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _updateComponentState(componentState: AdyenComponentEventState) {\n this._componentState = componentState;\n }\n\n private _validateCardData(): void {\n const adyenv2 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv2.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n const isEmptyString = (value: string) => value.toString().trim().length === 0;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n /**\n * For some reason adyen sdk doesn't return isValid for payment methods with select field in form(iDeal for example)\n * so we need to check state issuer field\n */\n if (\n Object.keys(cardComponent.state).length === 0 ||\n (!cardComponent.state.isValid && !cardComponent.state.issuer) ||\n // prevent empty sepa fields from being sent\n (cardComponent.props?.type === 'sepadirectdebit' &&\n cardComponent.state.data &&\n Object.values(cardComponent.state.data).some(isEmptyString))\n ) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { AccountState, AdyenComponentEventState } from '../types';\n\nexport default function isAccountState(param: AdyenComponentEventState): param is AccountState {\n const bankSupported = ['ideal', 'sepadirectdebit', 'directEbanking', 'giropay'];\n\n return bankSupported.indexOf((param as AccountState).data.paymentMethod.type) !== -1;\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV2ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV2PaymentStrategy from './adyenv2-payment-strategy';\n\nconst createAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV2PaymentStrategy(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV2PaymentStrategy, [{ gateway: 'adyenv2' }]);\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenV3HostWindow } from '../types';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenV3HostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.58.0/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-zgFNrGzbwuX5qJLys75cOUIGru/BoEzhGMyC07I3OSdHqXuhUfoDPVG03G+61oF4',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.58.0/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-e0EBlzLdOXxOJimp2uut2z1m98HS2cdhQw+OmeJDp7MRCPRNrQhjIWZiWiIscJvf',\n crossorigin: 'anonymous',\n },\n },\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentEventState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV3ActionType,\n AdyenV3PaymentInitializeOptions,\n AdyenV3PaymentMethodInitializationData,\n AdyenV3ScriptLoader,\n CardStateErrors,\n isBoletoState,\n isCardState,\n WithAdyenV3PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n BillingAddress,\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class Adyenv3PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentEventState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV3PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV3PaymentInitializeOptions,\n ): Promise {\n const { adyenv3 } = options;\n\n if (!adyenv3) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv3\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv3;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { environment, clientKey, paymentMethodsResponse, installmentOptions } =\n paymentMethod.initializationData || {};\n\n this._adyenClient = await this._scriptLoader.load({\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: true,\n },\n klarna_account: {\n useKlarnaWidget: true,\n },\n klarna_paynow: {\n useKlarnaWidget: true,\n },\n ...(installmentOptions\n ? {\n card: {\n installmentOptions: {\n showInstallmentAmounts: true,\n ...installmentOptions,\n },\n },\n }\n : {}),\n },\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n clientKey,\n paymentMethodsResponse,\n showPayButton: false,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n this._validateCardData();\n\n if (\n payment.methodId === 'klarna' ||\n payment.methodId === 'klarna_account' ||\n payment.methodId === 'klarna_paynow'\n ) {\n this._paymentComponent?.submit();\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState || {\n data: { paymentMethod: { type: payment.methodId } },\n };\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n\n let paymentToken = JSON.stringify({\n ...componentState.data.paymentMethod,\n type: payment.methodId,\n origin: window.location.origin,\n });\n\n if (payment.methodId === 'boletobancario' && isBoletoState(componentState)) {\n paymentToken = JSON.stringify({\n socialSecurityNumber: componentState.data.socialSecurityNumber,\n ...componentState.data.shopperName,\n type: payment.methodId,\n origin: window.location.origin,\n });\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: paymentToken,\n },\n ...(isCardState(componentState) && componentState.data.installments\n ? {\n installments: {\n value: componentState.data.installments.value,\n plan: componentState.data.installments.plan || 'regular',\n },\n }\n : {}),\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _updateComponentState(componentState: AdyenComponentEventState) {\n this._componentState = componentState;\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV3PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv3\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { additionalActionOptions } = this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete, widgetSize, onActionHandled } =\n additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onActionHandled: (additionalActionState) => {\n if (\n onActionHandled &&\n typeof onActionHandled === 'function' &&\n additionalActionState.componentType !== '3DS2Fingerprint'\n ) {\n onActionHandled();\n }\n },\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n challengeWindowSize: widgetSize || '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad && typeof onBeforeLoad === 'function') {\n onBeforeLoad(\n adyenAction.type === AdyenV3ActionType.ThreeDS2 ||\n adyenAction.type === AdyenV3ActionType.QRCode ||\n adyenAction.type === AdyenV3ActionType.Sdk,\n );\n }\n\n this._mountElement(additionalActionComponent, containerId);\n\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n firstName: prefillCardHolderName ? firstName : '',\n lastName: prefillCardHolderName ? lastName : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv3.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv3.options,\n styles: {\n ...adyenv3.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv3.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv3.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv3.validateCardFields(validateState),\n });\n\n try {\n this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n const billingAddress = this._paymentIntegrationService.getState().getBillingAddress();\n\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv3.options,\n showBrandsUnderCardNumber: false,\n billingAddressRequired: false,\n showEmailAddress: false,\n onChange: (componentState) => this._updateComponentState(componentState),\n onSubmit: (componentState) => this._updateComponentState(componentState),\n ...(billingAddress\n ? { data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName) }\n : {}),\n });\n\n try {\n this._mountElement(paymentComponent, adyenv3.containerId);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _validateCardData(): void {\n const adyenv3 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv3.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n if (Object.keys(cardComponent.state).length === 0 || !cardComponent.state.isValid) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n private _mountElement(adyenComponent: AdyenComponent, containerId: string): void {\n if (!document.getElementById(containerId)) {\n return;\n }\n\n adyenComponent.mount(`#${containerId}`);\n }\n}\n","import { AdyenComponentEventState, BoletoState } from '../types';\n\nexport default function isBoletoState(param: AdyenComponentEventState): param is BoletoState {\n return (\n (typeof param === 'object' && typeof (param as BoletoState).data.socialSecurityNumber) ===\n 'string' &&\n typeof (param as BoletoState).data.shopperName?.firstName === 'string' &&\n typeof (param as BoletoState).data.shopperName?.lastName === 'string'\n );\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV3ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV3PaymentStrategy from './adyenv3-payment-strategy';\n\nconst createAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV3PaymentStrategy(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV3PaymentStrategy, [{ gateway: 'adyenv3' }]);\n","import {\n AmountTransformer,\n Consignment,\n itemsRequireShipping,\n LineItemCategory,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Order,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n Affirm,\n AffirmAddress,\n AffirmDiscount,\n AffirmFailResponse,\n AffirmItem,\n AffirmRequestData,\n AffirmSuccessResponse,\n} from './affirm';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nexport default class AffirmPaymentStrategy implements PaymentStrategy {\n private affirm?: Affirm;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private affirmScriptLoader: AffirmScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const {\n clientToken,\n config: { testMode },\n } = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.affirm = await this.affirmScriptLoader.load(clientToken, testMode);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const methodId = payload.payment?.methodId;\n const { useStoreCredit } = payload;\n\n if (!this.affirm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this.paymentIntegrationService.submitOrder({ useStoreCredit }, options);\n\n const affirmCheckout = await this.initializeAffirmCheckout();\n\n const paymentPayload = {\n methodId,\n paymentData: { nonce: affirmCheckout.checkout_token },\n };\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n deinitialize(): Promise {\n if (this.affirm) {\n this.affirm = undefined;\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private initializeAffirmCheckout(): Promise {\n this.affirm?.checkout(this.getCheckoutInformation());\n\n return new Promise((resolve, reject) => {\n this.affirm?.checkout.open({\n onFail: (failObject: AffirmFailResponse) => {\n if (failObject.reason === 'canceled') {\n reject(new PaymentMethodCancelledError());\n } else {\n reject(new PaymentMethodInvalidError());\n }\n },\n onSuccess: (successObject) => {\n resolve(successObject);\n },\n });\n this.affirm?.ui.error.on('close', () => {\n reject(new PaymentMethodCancelledError());\n });\n });\n }\n\n private getCheckoutInformation(): AffirmRequestData {\n const state = this.paymentIntegrationService.getState();\n const config = state.getStoreConfig();\n const consignments = state.getConsignments();\n const order = state.getOrder();\n const cart = state.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!order) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const amountTransformer = new AmountTransformer(order.currency.decimalPlaces);\n const billingAddress = this.getBillingAddress();\n\n const retrievedShippingAddress = this.getShippingAddress();\n const shippingAddress =\n itemsRequireShipping(cart, config) && retrievedShippingAddress\n ? retrievedShippingAddress\n : billingAddress;\n\n return {\n merchant: {\n user_confirmation_url: config.links.checkoutLink,\n user_cancel_url: config.links.checkoutLink,\n user_confirmation_url_action: 'POST',\n },\n shipping: shippingAddress,\n billing: billingAddress,\n items: this.getItems(amountTransformer, order),\n metadata: {\n shipping_type: this.getShippingType(consignments),\n mode: 'modal',\n platform_type: 'BigCommerce',\n platform_version: '',\n platform_affirm: '',\n },\n discounts: this.getDiscounts(amountTransformer, order),\n order_id: order.orderId ? order.orderId.toString() : '',\n shipping_amount: amountTransformer.toInteger(order.shippingCostTotal),\n tax_amount: amountTransformer.toInteger(order.taxTotal),\n total: amountTransformer.toInteger(order.orderAmount),\n };\n }\n\n private getShippingType(consignments?: Consignment[]): string {\n if (!consignments) {\n return '';\n }\n\n const consignment = consignments[0];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return consignment?.selectedShippingOption ? consignment.selectedShippingOption.type : '';\n }\n\n private getBillingAddress(): AffirmAddress {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const billingInformation = {\n name: {\n first: billingAddress.firstName,\n last: billingAddress.lastName,\n full: `${billingAddress.firstName} ${billingAddress.lastName}`,\n },\n address: {\n line1: billingAddress.address1,\n line2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.stateOrProvinceCode,\n zipcode: billingAddress.postalCode,\n country: billingAddress.countryCode,\n },\n phone_number: billingAddress.phone,\n email: billingAddress.email,\n };\n\n return billingInformation;\n }\n\n private getShippingAddress(): AffirmAddress | undefined {\n const state = this.paymentIntegrationService.getState();\n const shippingAddress = state.getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n const shippingInformation = {\n name: {\n first: shippingAddress.firstName,\n last: shippingAddress.lastName,\n full: `${shippingAddress.firstName} ${shippingAddress.lastName}`,\n },\n address: {\n line1: shippingAddress.address1,\n line2: shippingAddress.address2,\n city: shippingAddress.city,\n state: shippingAddress.stateOrProvinceCode,\n zipcode: shippingAddress.postalCode,\n country: shippingAddress.countryCode,\n },\n phone_number: shippingAddress.phone,\n };\n\n return shippingInformation;\n }\n\n private getItems(amountTransformer: AmountTransformer, order: Order): AffirmItem[] {\n const items: AffirmItem[] = [];\n\n order.lineItems.physicalItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this.getCategories(item.categories),\n });\n });\n\n order.lineItems.digitalItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this.getCategories(item.categories),\n });\n });\n\n order.lineItems.giftCertificates.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: '',\n unit_price: amountTransformer.toInteger(item.amount),\n qty: 1,\n item_image_url: '',\n item_url: '',\n });\n });\n\n if (order.lineItems.customItems) {\n order.lineItems.customItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.listPrice),\n qty: item.quantity,\n item_image_url: '',\n item_url: '',\n });\n });\n }\n\n return items;\n }\n\n private getDiscounts(amountTransformer: AmountTransformer, order: Order): AffirmDiscount {\n const discounts: AffirmDiscount = {};\n\n order.coupons.forEach((line) => {\n if (line.discountedAmount > 0) {\n discounts[line.code] = {\n discount_amount: amountTransformer.toInteger(line.discountedAmount),\n discount_display_name: line.displayName,\n };\n }\n });\n\n if (order.discountAmount > 0) {\n discounts.DISCOUNTED_AMOUNT = {\n discount_amount: amountTransformer.toInteger(order.discountAmount),\n discount_display_name: 'discount',\n };\n }\n\n return discounts;\n }\n\n private getCategories(categories?: LineItemCategory[][]): string[][] {\n if (!categories) {\n return [[]];\n }\n\n return categories.map((categoryTree) => categoryTree.map((category) => category.name));\n }\n}\n","export interface Affirm {\n checkout: AffirmCheckout;\n ui: {\n error: {\n on(event: string, callback: () => void): void;\n };\n ready(callback: () => void): void;\n };\n}\n\nexport interface AffirmCheckout {\n (options: AffirmRequestData): void;\n open(modalOptions: AffirmCallback): void;\n init(): void;\n}\n\ninterface AffirmCallback {\n onFail(onFail: AffirmFailResponse): void;\n onSuccess(success: AffirmSuccessResponse): void;\n}\n\nexport interface AffirmHostWindow extends Window {\n affirm?: Affirm;\n}\n\nexport interface AffirmSuccessResponse {\n checkout_token: string;\n created: string;\n}\n\nexport interface AffirmFailResponse {\n reason: string;\n}\n\nexport interface AffirmRequestData {\n merchant: {\n user_confirmation_url: string;\n user_cancel_url: string;\n user_confirmation_url_action?: string;\n name?: string;\n };\n shipping: AffirmAddress;\n billing?: AffirmAddress;\n items: AffirmItem[];\n discounts: AffirmDiscount;\n metadata: {\n shipping_type: string;\n entity_name?: string;\n webhook_session_id?: string;\n mode?: string;\n platform_type: string;\n platform_version: string;\n platform_affirm: string;\n };\n order_id?: string;\n shipping_amount: number;\n tax_amount: number;\n total: number;\n}\n\nexport interface AffirmItem {\n display_name: string;\n sku: string;\n unit_price: number;\n qty: number;\n item_image_url: string;\n item_url: string;\n categories?: string[][];\n}\n\nexport interface AffirmDiscount {\n [key: string]: {\n discount_amount: number;\n discount_display_name: string;\n };\n}\n\nexport interface AffirmAddress {\n name: {\n first: string;\n last: string;\n full?: string;\n };\n address: {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n zipcode: string;\n country?: string;\n };\n phone_number?: string;\n email?: string;\n}\n\nexport enum AFFIRM_SCRIPTS {\n PROD = '//cdn1.affirm.com/js/v2/affirm.js',\n SANDBOX = '//cdn1-sandbox.affirm.com/js/v2/affirm.js',\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Affirm, AFFIRM_SCRIPTS, AffirmHostWindow } from './affirm';\nimport loadAffirmJS from './affirmJs';\n\nexport default class AffirmScriptLoader {\n constructor(public affirmWindow: AffirmHostWindow = window) {}\n\n load(apikey = '', testMode?: boolean): Promise {\n const scriptURI = testMode ? AFFIRM_SCRIPTS.SANDBOX : AFFIRM_SCRIPTS.PROD;\n\n loadAffirmJS(apikey, scriptURI);\n\n if (!this.affirmWindow.affirm) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(this.affirmWindow.affirm);\n }\n}\n","/* istanbul ignore file */\n\n/* eslint-disable prefer-rest-params */\n/* eslint-disable @typescript-eslint/no-empty-function */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable no-plusplus */\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-shadow */\n/* eslint-disable no-underscore-dangle */\n/**\n * Used this approach as Affirm uses snipped for initializing. Please refer to Affirm documentation in: https://docs.affirm.com/Integrate_Affirm/Direct_API#1._Add_Affirm.js\n */\nimport { Affirm, AffirmHostWindow } from './affirm';\n\ninterface AffirmConfig {\n public_api_key: string;\n script: string;\n}\n\nexport default function loadAffirmJS(apiKey: string, scriptURL: string) {\n const _AFFIRM_CONFIG: AffirmConfig = {\n public_api_key: apiKey,\n script: scriptURL,\n };\n\n (function foo(\n m: AffirmHostWindow | any,\n g: AffirmConfig,\n n: 'affirm',\n d: 'checkout',\n a: 'ui',\n e: 'script',\n h: 'ready',\n c: 'jsReady',\n ) {\n const b = m[n] || {};\n const k = document.createElement(e);\n const p = document.getElementsByTagName(e)[0];\n const l = function bar(a: Affirm | any, b: keyof Affirm, c: string) {\n return function baz() {\n a[b]._.push([c, arguments]);\n };\n };\n\n b[d] = l(b, d, 'set');\n\n const f = b[d];\n\n b[a] = {};\n b[a]._ = [];\n f._ = [];\n b._ = [];\n b[a][h] = l(b, a, h);\n\n b[c] = function qux() {\n b._.push([h, arguments]);\n };\n\n let a1 = 0;\n\n for (\n const c1 = 'set add save post open empty reset on off trigger ready setProduct'.split(\n ' ',\n );\n a1 < c1.length;\n a1++\n ) {\n f[c1[a1]] = l(b, d, c1[a1]);\n }\n\n let a2 = 0;\n\n for (const c2 = ['get', 'token', 'url', 'items']; a2 < c2.length; a2++) {\n f[c2[a2]] = function foobar() {};\n }\n\n k.async = !0;\n k.src = g[e];\n\n if (p.parentNode) {\n p.parentNode.insertBefore(k, p);\n }\n\n delete (g as Partial)[e];\n f(g);\n m[n] = b;\n })(window, _AFFIRM_CONFIG, 'affirm', 'checkout', 'ui', 'script', 'ready', 'jsReady');\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AffirmPaymentStrategy from './affirm-payment-strategy';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nconst createAffirmPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AffirmPaymentStrategy(paymentIntegrationService, new AffirmScriptLoader());\n};\n\nexport default toResolvableModule(createAffirmPaymentStrategy, [{ id: 'affirm' }]);\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the order finalization request\n * was not completed successfully.\n */\nexport default class OrderFinalizationNotCompletedError extends StandardError {\n constructor(message?: string) {\n super(message || 'The current order could not be finalized successfully');\n\n this.name = 'OrderFinalizationNotCompletedError';\n this.type = 'order_finalization_not_completed';\n }\n}\n","import {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotCompletedError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpayScriptLoader from './afterpay-script-loader';\nimport AfterpaySdk from './afterpay-sdk';\n\nexport default class AfterpayPaymentStrategy implements PaymentStrategy {\n private _afterpaySdk?: AfterpaySdk;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _afterpayScriptLoader: AfterpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(options.methodId, options.gatewayId);\n const currencyCode = state.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(paymentMethod, countryCode);\n }\n\n deinitialize(): Promise {\n if (this._afterpaySdk) {\n this._afterpaySdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { useStoreCredit } = payload;\n\n if (useStoreCredit !== undefined) {\n await this._paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this._loadPaymentMethod(gatewayId, methodId, options);\n\n const state = this._paymentIntegrationService.getState();\n\n await this._paymentIntegrationService.validateCheckout(state.getCheckout(), options);\n\n const currencyCode = state.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n this._redirectToAfterpay(countryCode, state.getPaymentMethod(methodId, gatewayId));\n\n // Afterpay will handle the rest of the flow so return a promise that doesn't really resolve\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Promise(() => {});\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n const config = state.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config?.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._paymentIntegrationService.submitOrder({}, options);\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._paymentIntegrationService.forgetCheckout(payment.providerId);\n await this._paymentIntegrationService.loadPaymentMethods();\n\n if (isRequestError(error)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-member-access\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n }\n\n private _redirectToAfterpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._afterpaySdk || !paymentMethod?.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._afterpaySdk.initialize({ countryCode });\n this._afterpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _mapCurrencyToISO2(currencyCode: string): string {\n const countryByCurrency: { [key: string]: string } = {\n AUD: 'AU',\n NZD: 'NZ',\n CAD: 'CA',\n USD: 'US',\n };\n\n return countryByCurrency[currencyCode] || 'AU';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n });\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Afterpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpaySdk from './afterpay-sdk';\nimport isAfterpayWindow from './is-afterpay-window';\n\nenum SCRIPTS_DEFAULT {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal-sandbox.afterpay.com/afterpay-async.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay-async.js',\n}\n\n/** Class responsible for loading the Afterpay SDK */\nexport default class AfterpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n /**\n * Loads the appropriate Afterpay SDK depending on the payment method data.\n *\n * @param {PaymentMethod} method the payment method data\n */\n async load(method: PaymentMethod, countryCode: string): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode);\n\n return this._scriptLoader.loadScript(scriptURI).then(() => {\n if (!isAfterpayWindow(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return window.AfterPay;\n });\n }\n\n private _getScriptURI(countryCode: string, testMode: boolean): string {\n if (countryCode === 'US') {\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import AfterpayWindow from './afterpay-window';\n\nexport default function isAfterpayWindow(window: Window): window is AfterpayWindow {\n return 'AfterPay' in window;\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpayPaymentStrategy from './afterpay-payment-strategy';\nimport AfterpayScriptLoader from './afterpay-script-loader';\n\nconst createAfterpayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AfterpayPaymentStrategy(\n paymentIntegrationService,\n new AfterpayScriptLoader(createScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createAfterpayPaymentStrategy, [\n { gateway: 'afterpay' },\n { id: 'afterpay' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n isAmazonPayAdditionalActionErrorBody,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CheckoutSettings,\n guard,\n InvalidArgumentError,\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StoreProfile,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithAmazonPayV2PaymentInitializeOptions } from './amazon-pay-v2-payment-initialize-options';\n\nexport default class AmazonPayV2PaymentStrategy implements PaymentStrategy {\n private _amazonPayButton?: HTMLDivElement;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAmazonPayV2PaymentInitializeOptions,\n ): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const initializationData = paymentMethod.initializationData || {};\n const { paymentToken = '', region = '', isButtonMicroTextDisabled } = initializationData;\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (this._isReadyToPay(paymentToken)) {\n if (amazonpay?.editButtonId) {\n this._bindEditButton(\n amazonpay.editButtonId,\n paymentToken,\n 'changePayment',\n this._isModalFlow(region),\n );\n }\n } else {\n const { id: containerId } = this._createContainer();\n\n this._amazonPayButton = this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: state,\n containerId,\n decoupleCheckoutInitiation: this._isOneTimeTransaction(\n features,\n region.toUpperCase(),\n ),\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n isButtonMicroTextDisabled,\n });\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const state = this.paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const initializationData = paymentMethod.initializationData || {};\n const { paymentToken = '', region = '' } = initializationData;\n\n if (\n this._isReadyToPay(paymentToken) ||\n this._isOneTimeTransaction(features, region.toUpperCase())\n ) {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: paymentToken || 'apb' },\n };\n\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n return;\n } catch (error) {\n if (!isRequestError(error) || !isAmazonPayAdditionalActionErrorBody(error.body)) {\n throw error;\n }\n\n const { additional_action_required: additionalAction } = error.body;\n const { redirect_url } = additionalAction.data;\n\n if (paymentToken) {\n return new Promise(() => window.location.assign(redirect_url));\n }\n\n this.amazonPayV2PaymentProcessor.prepareCheckout(\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n JSON.parse(redirect_url) as Required,\n );\n }\n }\n\n this._getAmazonPayButton().click();\n\n // Focus of parent window used to try and detect the user cancelling the Amazon log in modal\n // Should be refactored if/when Amazon add a modal close hook to their SDK\n if (this._isModalFlow(region)) {\n return new Promise((_, reject) => {\n const onFocus = () => {\n window.removeEventListener('focus', onFocus);\n reject(\n new PaymentMethodCancelledError(\n 'Shopper needs to login to Amazonpay to continue',\n ),\n );\n };\n\n window.addEventListener('focus', onFocus);\n });\n }\n\n return new Promise(noop);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.amazonPayV2PaymentProcessor.deinitialize();\n\n this._amazonPayButton = undefined;\n }\n\n private _bindEditButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n isModalFlow: boolean,\n ): void {\n const button = document.getElementById(buttonId);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (!isModalFlow) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => {\n void this._showLoadingSpinner();\n });\n }\n\n this.amazonPayV2PaymentProcessor.bindButton(buttonId, sessionId, changeAction);\n }\n\n private _isModalFlow(region: string) {\n return region === 'us';\n }\n\n private async _showLoadingSpinner(): Promise {\n await this.paymentIntegrationService.widgetInteraction(() => new Promise(noop));\n }\n\n private _createContainer(): HTMLElement {\n let container = document.getElementById('AmazonPayButton');\n\n if (container) {\n return container;\n }\n\n container = document.createElement('div');\n container.id = 'AmazonPayButton';\n container.style.display = 'none';\n\n return document.body.appendChild(container);\n }\n\n private _getAmazonPayButton() {\n return guard(\n this._amazonPayButton,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _isOneTimeTransaction(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n return (\n this.amazonPayV2PaymentProcessor.isPh4Enabled(features, storeCountryCode) &&\n features['INT-6399.amazon_pay_apb']\n );\n }\n\n private _isReadyToPay(paymentToken?: string): boolean {\n return !!paymentToken;\n }\n}\n","import { AmazonPayAdditionalActionErrorBody } from './amazon-pay-v2';\n\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nexport function isAmazonPayAdditionalActionErrorBody(\n errorBody: unknown,\n): errorBody is AmazonPayAdditionalActionErrorBody {\n return (\n typeof errorBody === 'object' &&\n errorBody !== null &&\n 'status' in errorBody &&\n 'additional_action_required' in errorBody &&\n (errorBody as AmazonPayAdditionalActionErrorBody).status === 'additional_action_required' &&\n 'data' in (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required &&\n 'redirect_url' in\n (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required.data &&\n typeof (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required.data\n .redirect_url === 'string'\n );\n}\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n","import { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2PaymentStrategy from './amazon-pay-v2-payment-strategy';\n\nconst createAmazonPayV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AmazonPayV2PaymentStrategy(\n paymentIntegrationService,\n createAmazonPayV2PaymentProcessor(),\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2PaymentStrategy, [{ id: 'amazonpay' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport { WithApplePayPaymentInitializeOptions } from './apple-pay-payment-initialize-options';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\ninterface ApplePayPromise {\n resolve(): void;\n reject(reason?: Error): void;\n}\n\nenum DefaultLabels {\n Shipping = 'Shipping',\n Subtotal = 'Subtotal',\n StoreCredit = 'Store Credit',\n}\n\nexport default class ApplePayPaymentStrategy implements PaymentStrategy {\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _storeCreditLabel: string = DefaultLabels.StoreCredit;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithApplePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n\n this._shippingLabel = options.applepay?.shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = options.applepay?.subtotalLabel || DefaultLabels.Subtotal;\n this._storeCreditLabel = options.applepay?.storeCreditLabel || DefaultLabels.StoreCredit;\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n const state = this._paymentIntegrationService.getState();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const request = this._getBaseRequest(state, paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n await this._paymentIntegrationService.submitOrder(\n {\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n\n applePaySession.begin();\n\n return new Promise((resolve, reject) => {\n this._handleApplePayEvents(applePaySession, paymentMethod, {\n resolve,\n reject,\n });\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _getBaseRequest(\n state: PaymentIntegrationSelectors,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const checkout = state.getCheckoutOrThrow();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const { grandTotal, isStoreCreditApplied, outstandingBalance } = checkout;\n\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n if (isStoreCreditApplied) {\n const { storeCredit } = state.getCustomerOrThrow();\n\n lineItems.push({\n label: this._storeCreditLabel,\n amount: `-${Math.min(grandTotal, storeCredit).toFixed(decimalPlaces)}`,\n });\n }\n\n return {\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems,\n total: {\n label: storeName,\n amount: `${outstandingBalance.toFixed(decimalPlaces)}`,\n type: 'final',\n },\n };\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n throw new Error('Merchant validation failed');\n }\n };\n\n applePaySession.oncancel = async () =>\n promise.reject(new PaymentMethodCancelledError('Continue with applepay'));\n\n applePaySession.onpaymentauthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod, promise);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n const { token } = event.payment;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n try {\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return promise.resolve();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return promise.reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n const state = this._paymentIntegrationService.getState();\n let braintreePaymentMethod =\n state.getPaymentMethod(ApplePayGatewayType.BRAINTREE_FASTLANE) ||\n state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (!braintreePaymentMethod) {\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n }\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayPaymentStrategy from './apple-pay-payment-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectPreviouslyUsedCard, BlueSnapDirectSdk } from '../types';\n\nexport default class BlueSnapDirect3ds {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n\n initialize(blueSnapSdk: BlueSnapDirectSdk) {\n this._blueSnapSdk = blueSnapSdk;\n }\n\n async initialize3ds(\n token: string,\n cardData: BlueSnapDirectPreviouslyUsedCard,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n return new Promise((resolve, reject) => {\n blueSnapSdk.threeDsPaymentsSetup(token, (sdkResponse) => {\n const code = sdkResponse.code;\n\n if (code === '1') {\n return resolve(sdkResponse.threeDSecure.threeDSecureReferenceId);\n }\n\n return reject(new PaymentMethodFailedError());\n });\n\n blueSnapSdk.threeDsPaymentsSubmitData(cardData);\n });\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","// copied from packages/core/src/hosted-form/hosted-field-type.ts\n\nenum HostedFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n CardExpiryVerification = 'cardExpiryVerification',\n}\n\nexport default HostedFieldType;\n","import {\n HostedCardFieldOptionsMap,\n HostedFieldOptionsMap,\n HostedFieldType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return HostedFieldType.CardNumber in fields;\n}\n","import {\n HostedFieldOptionsMap,\n HostedFieldType,\n HostedStoredCardFieldOptionsMap,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedStoredCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardCodeVerification in fields ||\n HostedFieldType.CardNumberVerification in fields\n );\n}\n","import { WithCreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectSdk, BlueSnapDirectThreeDSecureData } from '../types';\nimport isHostedCardFieldOptionsMap from '../utils/is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from '../utils/is-hosted-stored-card-field-options-map';\n\nimport BlueSnapDirect3ds from './bluesnap-direct-3ds';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nexport default class BlueSnapDirectCreditCardPaymentStrategy implements PaymentStrategy {\n private _paymentFieldsToken?: string;\n private _shouldUseHostedFields?: boolean;\n private _blueSnapSdk?: BlueSnapDirectSdk;\n\n constructor(\n private _scriptLoader: BlueSnapDirectScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _blueSnapDirectHostedForm: BlueSnapDirectHostedForm,\n private _blueSnapDirect3ds: BlueSnapDirect3ds,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, creditCard } = options;\n\n if (!gatewayId || !creditCard) {\n throw new InvalidArgumentError();\n }\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId, bigpayToken: creditCard.bigpayToken },\n });\n\n const {\n config: { testMode, is3dsEnabled },\n clientToken,\n } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n this._blueSnapSdk = await this._scriptLoader.load(testMode);\n\n this._paymentFieldsToken = clientToken;\n this._shouldUseHostedFields =\n isHostedCardFieldOptionsMap(creditCard.form.fields) ||\n (isHostedStoredCardFieldOptionsMap(creditCard.form.fields) &&\n !!creditCard.form.fields.cardNumberVerification);\n\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk, creditCard.form.fields);\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n }\n }\n\n async execute(payload: OrderRequestBody): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._blueSnapSdk) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData } = payload.payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const pfToken = this._getPaymentFieldsToken();\n let threeDSecureReferenceId;\n\n const { is3dsEnabled } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payload.payment.methodId, payload.payment.gatewayId).config;\n\n const bluesnapSubmitedForm = this._shouldUseHostedFields\n ? await this._blueSnapDirectHostedForm\n .validate()\n .submit(\n is3dsEnabled ? this._getBlueSnapDirectThreeDSecureData() : undefined,\n !(isHostedInstrumentLike(paymentData) && isVaultedInstrument(paymentData)),\n )\n : undefined;\n\n await this._paymentIntegrationService.submitOrder();\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n this._paymentFieldsToken &&\n paymentData.instrumentId\n ) {\n if (is3dsEnabled) {\n this._blueSnapDirect3ds.initialize(this._blueSnapSdk);\n\n const { last4, brand } = this._paymentIntegrationService\n .getState()\n .getCardInstrumentOrThrow(paymentData.instrumentId);\n\n const previouslyUsedCard = {\n last4Digits: last4,\n ccType: brand.toUpperCase(),\n ...this._getBlueSnapDirectThreeDSecureData(),\n };\n\n threeDSecureReferenceId = await this._blueSnapDirect3ds.initialize3ds(\n this._paymentFieldsToken,\n previouslyUsedCard,\n );\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n instrumentId: paymentData.instrumentId,\n ...(this._shouldUseHostedFields ? { nonce: pfToken } : {}),\n ...(threeDSecureReferenceId\n ? { deviceSessionId: threeDSecureReferenceId }\n : {}),\n shouldSetAsDefaultInstrument: !!shouldSetAsDefaultInstrument,\n },\n });\n\n return;\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n pfToken,\n cardHolderName:\n bluesnapSubmitedForm && bluesnapSubmitedForm.cardHolderName,\n }),\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n private _getBlueSnapDirectThreeDSecureData(): BlueSnapDirectThreeDSecureData {\n const {\n getBillingAddress,\n getShippingAddress,\n getCustomer,\n getCheckoutOrThrow,\n getCartOrThrow,\n } = this._paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const shippingAddress = getShippingAddress();\n const email = getCustomer()?.email || billingAddress?.email;\n const phone = billingAddress?.phone || shippingAddress?.phone;\n\n return {\n amount: getCheckoutOrThrow().outstandingBalance,\n currency: getCartOrThrow().currency.code,\n ...(email && { email }),\n ...(phone && { phone }),\n ...(billingAddress && {\n billingFirstName: billingAddress.firstName,\n billingLastName: billingAddress.lastName,\n billingCountry: billingAddress.countryCode,\n billingCity: billingAddress.city,\n billingAddress: `${billingAddress.address1} ${billingAddress.address2}`.trim(),\n billingZip: billingAddress.postalCode,\n }),\n ...(shippingAddress && {\n shippingFirstName: shippingAddress.firstName,\n shippingLastName: shippingAddress.lastName,\n shippingCountry: shippingAddress.countryCode,\n shippingCity: shippingAddress.city,\n shippingAddress: `${shippingAddress.address1} ${shippingAddress.address2}`.trim(),\n shippingZip: shippingAddress.postalCode,\n }),\n };\n }\n\n private _getPaymentFieldsToken(): string {\n return guard(\n this._paymentFieldsToken,\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n }\n}\n","export type BluesnapDirectNocInputAllowedStyle = Pick<\n CSSStyleDeclaration,\n 'color' | 'fontFamily' | 'fontSize' | 'fontWeight'\n>;\n\nexport interface BlueSnapDirectStyleDeclaration {\n [k: string]: string;\n}\n\nexport interface BlueSnapDirectStyle {\n '.invalid'?: BlueSnapDirectStyleDeclaration;\n ':focus'?: BlueSnapDirectStyleDeclaration;\n input?: BlueSnapDirectStyleDeclaration;\n}\n\nexport enum BlueSnapDirectCardType {\n AMEX = 'american-express',\n CHINA_UNION_PAY = 'unionpay',\n DINERS = 'diners-club',\n DISCOVER = 'discover',\n JCB = 'jcb',\n MASTERCARD = 'mastercard',\n UNKNOWN = 'unknown',\n VISA = 'visa',\n}\n\nexport type BlueSnapDirectCardTypeValues = keyof typeof BlueSnapDirectCardType;\n\nexport enum BlueSnapDirectEventOrigin {\n ON_BLUR = 'onBlur',\n ON_SUBMIT = 'onSubmit',\n}\n\nexport enum BlueSnapDirectErrorDescription {\n EMPTY = 'empty',\n INVALID = 'invalid',\n THREE_DS_NOT_ENABLED = '3D Secure is not enabled',\n}\n\nexport type BlueSnapDirectInputValidationErrorDescription = Extract<\n BlueSnapDirectErrorDescription,\n BlueSnapDirectErrorDescription.EMPTY | BlueSnapDirectErrorDescription.INVALID\n>;\n\nexport enum BlueSnapDirectErrorCode {\n CC_NOT_SUPORTED = '22013',\n ERROR_403 = '403',\n ERROR_404 = '404',\n ERROR_500 = '500',\n INVALID_OR_EMPTY = '10',\n SESSION_EXPIRED = '400',\n THREE_DS_AUTH_FAILED = '14101',\n THREE_DS_CLIENT_ERROR = '14103',\n THREE_DS_MISSING_FIELDS = '14102',\n THREE_DS_NOT_ENABLED = '14100',\n TOKEN_EXPIRED = '14040',\n TOKEN_NOT_ASSOCIATED = '14042',\n TOKEN_NOT_FOUND = '14041',\n}\n\nexport enum BlueSnapDirectHostedFieldTagId {\n CardCode = 'cvv',\n CardExpiry = 'exp',\n CardName = 'noc',\n CardNumber = 'ccn',\n}\n\nexport interface BlueSnapDirectHostedPaymentFieldsOptions {\n token: string;\n onFieldEventHandler?: {\n setupComplete?: () => void;\n threeDsChallengeExecuted?: () => void;\n onFocus?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onBlur?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onError?: (\n tagId: BlueSnapDirectHostedFieldTagId | undefined,\n errorCode: BlueSnapDirectErrorCode,\n errorDescription: BlueSnapDirectErrorDescription | undefined,\n eventOrigin: BlueSnapDirectEventOrigin | undefined,\n ) => void;\n onType?: (\n tagId: BlueSnapDirectHostedFieldTagId,\n cardType: BlueSnapDirectCardTypeValues,\n cardData: BlueSnapDirectCardData | undefined,\n ) => void;\n onEnter?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onValid?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n };\n ccnPlaceHolder?: string;\n cvvPlaceHolder?: string;\n expPlaceHolder?: string;\n style?: BlueSnapDirectStyle;\n '3DS'?: boolean;\n}\n\ninterface BlueSnapDirectCallback {\n statusCode: string;\n transactionFraudInfo: {\n fraudSessionId: string;\n };\n}\n\ninterface BlueSnapDirectCardData {\n binCategory: string;\n cardSubType: string;\n ccBin: string;\n ccType: string;\n isRegulatedCard: string;\n issuingCountry: string;\n last4Digits: string;\n}\n\nexport interface BlueSnapDirectCallbackCardData extends BlueSnapDirectCardData {\n cardCategory: string;\n exp: string;\n}\n\ninterface BlueSnapDirectCallbackData extends BlueSnapDirectCallback {\n cardData: BlueSnapDirectCallbackCardData;\n}\n\nexport interface WithBlueSnapDirectCardHolderName {\n cardHolderName?: string;\n}\n\ninterface BlueSnapDirectSubmitError {\n errorCode: string;\n errorDescription: string;\n eventType: string;\n tagId: string;\n}\n\nexport interface BlueSnapDirectCallbackError extends BlueSnapDirectCallback {\n error: BlueSnapDirectSubmitError[];\n}\n\nexport type BlueSnapDirectCallbackResults =\n | BlueSnapDirectCallbackData\n | BlueSnapDirectCallbackError;\n\nexport interface BlueSnapDirectThreeDSecureData {\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirectSdk {\n hostedPaymentFieldsCreate(options: BlueSnapDirectHostedPaymentFieldsOptions): void;\n hostedPaymentFieldsSubmitData(\n callback: (results: BlueSnapDirectCallbackResults) => void,\n threeDSecureData?: BlueSnapDirectThreeDSecureData,\n ): void;\n threeDsPaymentsSetup(\n token: string,\n callback: (reponse: BlueSnapDirect3dsCallbackResponse) => void,\n ): void;\n threeDsPaymentsSubmitData(cardData: BlueSnapDirectPreviouslyUsedCard): void;\n}\n\nexport interface BlueSnapDirectPreviouslyUsedCard {\n last4Digits?: string;\n ccType?: string;\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirect3dsCallbackResponse {\n code: string;\n cardData: BlueSnapDirectCallbackCardData;\n threeDSecure: {\n authResult: string;\n threeDSecureReferenceId: string;\n };\n}\n\nexport interface BlueSnapDirectHostWindow extends Window {\n bluesnap?: BlueSnapDirectSdk;\n}\n\nexport interface BlueSnapDirectStyleProps {\n border?: string;\n height?: string;\n width?: string;\n}\n\nexport interface BlueSnapDirectRedirectResponseProviderData {\n [key: string]: string;\n merchantid: string;\n}\n\nexport interface BlueSnapDirectRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data?: string;\n };\n}\n\n/**\n * A set of options that are required to initialize the BlueSnap V2 payment\n * method.\n *\n * The payment step is done through a web page via an iframe provided by the\n * strategy.\n *\n * ```html\n * \n *
\n *\n * \n * \n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'bluesnapDirect',\n * bluesnapDirect: {\n * onLoad: (iframe) => {\n * document.getElementById('container')\n * .appendChild(iframe);\n *\n * document.getElementById('cancel-button')\n * .addEventListener('click', () => {\n * document.getElementById('container').innerHTML = '';\n * });\n * },\n * },\n * });\n * ```\n */\nexport interface BlueSnapDirectAPMInitializeOptions {\n /**\n * A set of CSS properties to apply to the iframe.\n */\n style?: BlueSnapDirectStyleProps;\n\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param iframe - The iframe element containing the payment web page\n * provided by the strategy.\n * @param cancel - A function, when called, will cancel the payment\n * process and remove the iframe.\n */\n onLoad(iframe: HTMLIFrameElement, cancel: () => void): void;\n}\n\nexport interface WithBlueSnapDirectAPMPaymentInitializeOptions {\n /**\n * The options that are required to initialize the Apple Pay payment\n * method. They can be omitted unless you need to support Apple Pay.\n */\n bluesnapdirect?: BlueSnapDirectAPMInitializeOptions;\n}\n","import { HostedFieldType } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostedFieldTagId as HostedFieldTagId } from './types';\n\nexport const BlueSnapHostedFieldType: {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber;\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry;\n [HostedFieldTagId.CardName]: HostedFieldType.CardName;\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode;\n} = {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber,\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry,\n [HostedFieldTagId.CardName]: HostedFieldType.CardName,\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode,\n};\n\nexport const CREDIT_CARD_ERRORS = {\n empty: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date is required',\n type: 'required',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n invalid: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date must be a valid future date in MM / YY format',\n type: 'invalid_card_expiry',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n};\n","import { kebabCase } from 'lodash';\n\nimport { CreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldOptionsMap,\n HostedFieldStylesMap,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType } from '../bluesnap-direct-constants';\nimport {\n BlueSnapDirectSdk,\n BlueSnapDirectStyle,\n BlueSnapDirectCallbackCardData as CallbackCardData,\n BlueSnapDirectCallbackError as CallbackError,\n BlueSnapDirectCallbackResults as CallbackResults,\n WithBlueSnapDirectCardHolderName as CardHolderName,\n BlueSnapDirectCardType as CardType,\n BlueSnapDirectCardTypeValues as CardTypeValues,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectThreeDSecureData as ThreeDSecureData,\n} from '../types';\nimport isValidationErrorDescription from '../utils/is-bluesnap-direct-input-validation-error-description';\nimport isHostedCardFieldOptionsMap from '../utils/is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from '../utils/is-hosted-stored-card-field-options-map';\n\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\n\nexport default class BlueSnapDirectHostedForm {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n private _onValidate: HostedFormOptions['onValidate'];\n\n constructor(\n private _nameOnCardInput: BluesnapDirectNameOnCardInput,\n private _hostedInputValidator: BlueSnapHostedInputValidator,\n ) {}\n\n initialize(blueSnapSdk: BlueSnapDirectSdk, fields?: HostedFieldOptionsMap) {\n this._blueSnapSdk = blueSnapSdk;\n\n if (!fields) {\n return;\n }\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._hostedInputValidator.initialize();\n\n return;\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields) && !!fields.cardNumberVerification) {\n this._hostedInputValidator.initializeValidationFields();\n }\n }\n\n async attach(\n paymentFieldsToken: string,\n { form: { fields, ...callbacksAndStyles } }: CreditCardPaymentInitializeOptions,\n enable3DS = false,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n if (!isHostedCardFieldOptionsMap(fields) && !isHostedStoredCardFieldOptionsMap(fields)) {\n throw new InvalidArgumentError(\n 'Field options must be of type HostedCardFieldOptionsMap',\n );\n }\n\n this._onValidate = callbacksAndStyles.onValidate;\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._setCustomBlueSnapAttributes(fields);\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields)) {\n this._setCustomStoredCardsBlueSnapAttributes(fields);\n }\n\n return new Promise((resolve) => {\n const options = this._getHostedPaymentFieldsOptions(\n paymentFieldsToken,\n fields,\n callbacksAndStyles,\n resolve,\n enable3DS,\n );\n\n blueSnapSdk.hostedPaymentFieldsCreate(options);\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._nameOnCardInput.attach(\n options,\n fields.cardName.accessibilityLabel,\n fields.cardName.placeholder,\n );\n }\n });\n }\n\n validate(): this {\n const results = this._hostedInputValidator.validate();\n\n this._onValidate?.(results);\n\n if (!results.isValid) {\n const details = Object.entries(results.errors).reduce(\n (result, [key, value]: [string, HostedInputValidateErrorData[]]) => ({\n ...result,\n [key]: value.map(({ message, type }) => ({ message, type })),\n }),\n {},\n );\n\n throw new PaymentInvalidFormError(details);\n }\n\n return this;\n }\n\n submit(\n threeDSecureData?: ThreeDSecureData,\n shouldSendName = false,\n ): Promise {\n return new Promise((resolve, reject) =>\n this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(\n (data: CallbackResults) =>\n this._isBlueSnapDirectCallbackError(data)\n ? reject(\n new PaymentMethodFailedError(\n data.statusCode === ErrorCode.THREE_DS_AUTH_FAILED\n ? data.error[0].errorDescription\n : `Submission failed with status: ${\n data.statusCode\n } and errors: ${JSON.stringify(data.error)}`,\n ),\n )\n : resolve({\n ...data.cardData,\n ...(shouldSendName\n ? { cardHolderName: this._nameOnCardInput.getValue() }\n : {}),\n }),\n threeDSecureData,\n ),\n );\n }\n\n detach(): void {\n this._nameOnCardInput.detach();\n }\n\n private _isBlueSnapDirectCallbackError(data: CallbackResults): data is CallbackError {\n return 'error' in data;\n }\n\n private _getHostedPaymentFieldsOptions(\n token: string,\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n {\n onFocus,\n onBlur,\n onValidate,\n onCardTypeChange,\n onEnter,\n styles,\n }: Omit,\n resolve: () => void,\n enable3DS: boolean,\n ): HostedPaymentFieldsOptions {\n return {\n token,\n onFieldEventHandler: {\n setupComplete: () => resolve(),\n onFocus: this._usetUiEventCallback(onFocus),\n onBlur: this._usetUiEventCallback(onBlur),\n onError: this._handleError(onValidate),\n onType: (_tagId: HostedFieldTagId, cardType: CardTypeValues) =>\n onCardTypeChange?.({ cardType: CardType[cardType] }),\n onEnter: this._usetUiEventCallback(onEnter),\n onValid: (tagId: HostedFieldTagId) =>\n onValidate?.(this._hostedInputValidator.validate({ tagId })),\n },\n ...(isHostedCardFieldOptionsMap(fields) && {\n ccnPlaceHolder: fields.cardNumber.placeholder || '',\n cvvPlaceHolder: fields.cardCode?.placeholder || '',\n expPlaceHolder: fields.cardExpiry.placeholder || 'MM / YY',\n }),\n ...(styles && { style: this._mapStyles(styles) }),\n '3DS': enable3DS,\n };\n }\n\n private _mapStyles({\n default: input,\n error,\n focus,\n }: HostedFieldStylesMap): BlueSnapDirectStyle {\n return Object.entries({\n ...(input && { input }),\n ...(error && { '.invalid': error }),\n ...(focus && { ':focus': focus }),\n }).reduce((result, [selector, declaration]) => {\n return {\n ...result,\n [selector]: Object.entries(declaration).reduce(\n (declarationBlock, [property, value]) => ({\n ...declarationBlock,\n [kebabCase(property)]: value,\n }),\n {},\n ),\n };\n }, {});\n }\n\n private _handleError(\n onValidate: HostedFormOptions['onValidate'],\n ): (\n tagId: HostedFieldTagId | undefined,\n errorCode: ErrorCode,\n errorDescription: ErrorDescription | undefined,\n eventOrigin: EventOrigin | undefined,\n ) => void {\n return (tagId, errorCode, errorDescription, eventOrigin) => {\n if (errorCode === ErrorCode.INVALID_OR_EMPTY) {\n if (tagId && isValidationErrorDescription(errorDescription)) {\n return onValidate?.(\n this._hostedInputValidator.validate({ tagId, errorDescription }),\n );\n }\n }\n\n throw new PaymentMethodFailedError(\n `An unexpected error has occurred: ${JSON.stringify({\n tagId,\n errorCode,\n errorDescription,\n eventOrigin,\n })}`,\n );\n };\n }\n\n private _usetUiEventCallback(\n callback?: (\n data: HostedFieldBlurEventData | HostedFieldEnterEventData | HostedFieldFocusEventData,\n ) => void,\n ): (tagId: HostedFieldTagId) => void {\n return (tagId) => {\n if (callback) {\n callback({ fieldType: BlueSnapHostedFieldType[tagId] });\n }\n };\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _setCustomBlueSnapAttributes(fields: HostedCardFieldOptionsMap): void {\n const { cardNumber, cardExpiry, cardCode, cardName } = fields;\n\n const cardNumberContainer = document.getElementById(cardNumber.containerId);\n const cardExpiryContainer = document.getElementById(cardExpiry.containerId);\n const cardCodeContainer = cardCode && document.getElementById(cardCode.containerId);\n const cardNameContainer = document.getElementById(cardName.containerId);\n\n if (\n !cardNumberContainer ||\n !cardExpiryContainer ||\n !cardCodeContainer ||\n !cardNameContainer\n ) {\n throw new InvalidArgumentError(\n 'Unable to create hosted payment fields to invalid HTML container elements.',\n );\n }\n\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n cardExpiryContainer.dataset.bluesnap = HostedFieldTagId.CardExpiry;\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n cardNameContainer.dataset.bluesnap = HostedFieldTagId.CardName;\n }\n\n private _setCustomStoredCardsBlueSnapAttributes(fields: HostedStoredCardFieldOptionsMap): void {\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n const cardNumberContainer =\n cardNumberVerification && document.getElementById(cardNumberVerification.containerId);\n const cardCodeContainer =\n cardCodeVerification && document.getElementById(cardCodeVerification.containerId);\n\n if (!cardNumberContainer && !cardCodeContainer) {\n return;\n }\n\n if (cardNumberContainer) {\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n }\n\n if (cardCodeContainer) {\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n }\n }\n}\n","import {\n BlueSnapDirectErrorDescription,\n BlueSnapDirectInputValidationErrorDescription,\n} from '../types';\n\nexport default function isBlueSnapDirectInputValidationErrorDescription(\n errorDescription?: BlueSnapDirectErrorDescription,\n): errorDescription is BlueSnapDirectInputValidationErrorDescription {\n if (errorDescription === undefined) {\n return false;\n }\n\n return [BlueSnapDirectErrorDescription.EMPTY, BlueSnapDirectErrorDescription.INVALID].includes(\n errorDescription,\n );\n}\n","import {\n HostedFieldType,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInputValidateResults,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType, CREDIT_CARD_ERRORS } from '../bluesnap-direct-constants';\nimport {\n BlueSnapDirectInputValidationErrorDescription as ErrorDescription,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n} from '../types';\n\nexport default class BlueSnapHostedInputValidator {\n private _errors: HostedInputValidateErrorDataMap = {};\n\n initialize(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardExpiry: [CREDIT_CARD_ERRORS.empty.cardExpiry],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n cardName: [CREDIT_CARD_ERRORS.empty.cardName],\n };\n }\n\n initializeValidationFields(): void {\n this._errors = {\n cardNumberVerification: [CREDIT_CARD_ERRORS.empty.cardNumber],\n };\n }\n\n validate(error?: {\n tagId: HostedFieldTagId;\n errorDescription?: ErrorDescription;\n }): HostedInputValidateResults {\n if (error) {\n this._updateErrors(error.tagId, error.errorDescription);\n }\n\n return {\n isValid: Object.values(this._errors).every(\n (errorData: HostedInputValidateErrorData[]) => errorData.length === 0,\n ),\n errors: this._errors,\n };\n }\n\n private _updateErrors(tagId: HostedFieldTagId, errorDescription?: ErrorDescription): void {\n const fieldType = this._errors.cardNumberVerification\n ? HostedFieldType.CardNumberVerification\n : BlueSnapHostedFieldType[tagId];\n\n this._errors[fieldType] = errorDescription\n ? [CREDIT_CARD_ERRORS[errorDescription][fieldType]]\n : [];\n }\n}\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BluesnapDirectNocInputAllowedStyle as AllowedStyle,\n BlueSnapDirectStyle,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectStyleDeclaration as StyleDeclaration,\n} from '../types';\nimport isArrayOfAllowedProps from '../utils/is-array-of-allowed-props';\n\nexport default class BluesnapDirectNameOnCardInput {\n private _input?: HTMLInputElement;\n private _style?: BlueSnapDirectStyle;\n\n attach(\n {\n style,\n onFieldEventHandler: { onFocus, onBlur, onValid, onError, onEnter } = {},\n }: HostedPaymentFieldsOptions,\n accessibilityLabel?: string,\n placeholder?: string,\n ): void {\n this._style = style;\n\n this._create();\n\n this._getInput().addEventListener('focus', this._handleFocus(onFocus));\n this._getInput().addEventListener('blur', this._handleBlur(onBlur, onValid, onError));\n this._getInput().addEventListener('enter', this._handleEnter(onEnter));\n\n if (accessibilityLabel) {\n this._getInput().setAttribute('aria-label', accessibilityLabel);\n }\n\n if (placeholder) {\n this._getInput().placeholder = placeholder;\n }\n\n document.querySelector('[data-bluesnap=\"noc\"]')?.appendChild(this._getInput());\n }\n\n getValue(): string {\n return this._getInput().value;\n }\n\n detach(): void {\n if (this._input) {\n this._input.remove();\n this._input = undefined;\n }\n }\n\n private _handleFocus(\n onFocus: Required['onFieldEventHandler']['onFocus'],\n ): (event: Event) => void {\n return () => {\n this._applyStyles(this._style?.[':focus']);\n\n onFocus?.(HostedFieldTagId.CardName);\n };\n }\n\n private _handleBlur(\n onBlur: Required['onFieldEventHandler']['onBlur'],\n onValid: Required['onFieldEventHandler']['onValid'],\n onError: Required['onFieldEventHandler']['onError'],\n ): (event: Event) => void {\n return ({ target }) => {\n onBlur?.(HostedFieldTagId.CardName);\n\n if (target instanceof HTMLInputElement) {\n if (/\\w{1,200}/.test(target.value)) {\n this._applyStyles(this._style?.input);\n\n onValid?.(HostedFieldTagId.CardName);\n } else {\n this._applyStyles(this._style?.['.invalid']);\n\n onError?.(\n HostedFieldTagId.CardName,\n ErrorCode.INVALID_OR_EMPTY,\n ErrorDescription.EMPTY,\n EventOrigin.ON_BLUR,\n );\n }\n }\n };\n }\n\n private _handleEnter(\n onEnter: Required['onFieldEventHandler']['onEnter'],\n ): (event: Event) => void {\n return () => onEnter?.(HostedFieldTagId.CardName);\n }\n\n private _applyStyles(styles: StyleDeclaration = {}): void {\n const allowedStyle: AllowedStyle = {\n color: styles.color,\n fontFamily: styles['font-family'],\n fontSize: styles['font-size'],\n fontWeight: styles['font-weight'],\n };\n const styleKeys = Object.keys(allowedStyle);\n\n if (isArrayOfAllowedProps(styleKeys)) {\n styleKeys.forEach((key) => {\n if (!allowedStyle[key]) {\n return;\n }\n\n this._getInput().style[key] = allowedStyle[key] || '';\n });\n }\n }\n\n private _configureInput(): void {\n this._getInput().autocomplete = 'cc-name';\n this._getInput().id = HostedFieldTagId.CardName;\n this._getInput().inputMode = 'text';\n this._getInput().maxLength = 200;\n this._getInput().style.backgroundColor = 'transparent';\n this._getInput().style.border = '0';\n this._getInput().style.height = '100%';\n this._getInput().style.margin = '0';\n this._getInput().style.outline = 'none';\n this._getInput().style.padding = '0';\n this._getInput().style.width = '100%';\n this._getInput().type = 'text';\n }\n\n private _getInput(): HTMLInputElement {\n return guard(\n this._input,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _create(): void {\n this._input = document.createElement('input');\n this._configureInput();\n this._applyStyles(this._style?.input);\n }\n}\n","import { BluesnapDirectNocInputAllowedStyle } from '../types';\n\nexport default function isArrayOfAllowedProps(\n fields: string[],\n): fields is Array {\n return fields.every((field) =>\n ['color', 'fontFamily', 'fontSize', 'fontWeight'].includes(field),\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostWindow, BlueSnapDirectSdk } from '../types';\n\nexport enum BlueSnapDirectSdkEnv {\n PRODUCTION = 'https://pay.bluesnap.com/web-sdk/5/bluesnap.js',\n SANDBOX = 'https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js',\n}\n\nexport default class BlueSnapDirectScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BlueSnapDirectHostWindow = window,\n ) {}\n\n async load(testMode = false): Promise {\n if (this._window.bluesnap) {\n return this._window.bluesnap;\n }\n\n await this._scriptLoader.loadScript(\n testMode ? BlueSnapDirectSdkEnv.SANDBOX : BlueSnapDirectSdkEnv.PRODUCTION,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this._window.bluesnap) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.bluesnap;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirect3ds from './bluesnap-direct-3ds';\nimport BlueSnapDirectCreditCardPaymentStrategy from './bluesnap-direct-credit-card-payment-strategy';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nconst createBlueSnapDirectCreditCardPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectCreditCardPaymentStrategy\n> = (paymentIntegrationService) =>\n new BlueSnapDirectCreditCardPaymentStrategy(\n new BlueSnapDirectScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n new BlueSnapDirectHostedForm(\n new BluesnapDirectNameOnCardInput(),\n new BlueSnapHostedInputValidator(),\n ),\n new BlueSnapDirect3ds(),\n );\n\nexport default toResolvableModule(createBlueSnapDirectCreditCardPaymentStrategy, [\n { id: 'credit_card', gateway: 'bluesnapdirect' },\n]);\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectRedirectResponse } from '../types';\nimport {\n isEcpInstrument,\n isIdealInstrument,\n isPayByBankInstrument,\n isSepaInstrument,\n} from '../utils/is-bluesnap-direct-instrument';\nimport isBlueSnapDirectRedirectResponseProviderData from '../utils/is-bluesnap-direct-provider-data';\n\nexport default class BlueSnapDirectAPMPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody): Promise {\n const paymentPayload = this._formatePaymentPayload(payload);\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (this._isBlueSnapDirectRedirectResponse(error)) {\n const providerData: unknown =\n error.body.provider_data && JSON.parse(error.body.provider_data);\n\n let frameUrl = error.body.additional_action_required.data.redirect_url;\n\n if (isBlueSnapDirectRedirectResponseProviderData(providerData)) {\n const providerDataQuery = new URLSearchParams(providerData).toString();\n\n frameUrl = `${frameUrl}&${providerDataQuery}`;\n }\n\n return new Promise(() => window.location.replace(frameUrl));\n }\n\n return Promise.reject(error);\n }\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _formatePaymentPayload({ payment }: OrderRequestBody) {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (\n payment.paymentData &&\n isVaultedInstrument(payment.paymentData) &&\n isHostedInstrumentLike(payment.paymentData)\n ) {\n return {\n ...payment,\n paymentData: {\n instrumentId: payment.paymentData.instrumentId,\n shouldSetAsDefaultInstrument:\n !!payment.paymentData.shouldSetAsDefaultInstrument,\n },\n };\n }\n\n if (isEcpInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n ecp: {\n account_number: payment.paymentData.accountNumber,\n account_type: payment.paymentData.accountType,\n shopper_permission: payment.paymentData.shopperPermission,\n routing_number: payment.paymentData.routingNumber,\n },\n vault_payment_instrument: payment.paymentData.shouldSaveInstrument,\n set_as_default_stored_instrument:\n payment.paymentData.shouldSetAsDefaultInstrument,\n },\n },\n };\n }\n\n if (isSepaInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n sepa_direct_debit: {\n iban: payment.paymentData.iban,\n first_name: payment.paymentData.firstName,\n last_name: payment.paymentData.lastName,\n shopper_permission: payment.paymentData.shopperPermission,\n },\n vault_payment_instrument: payment.paymentData.shouldSaveInstrument,\n set_as_default_stored_instrument:\n payment.paymentData.shouldSetAsDefaultInstrument,\n },\n },\n };\n }\n\n if (isIdealInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n ideal: {\n bic: payment.paymentData.bic,\n },\n },\n },\n };\n }\n\n if (isPayByBankInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n pay_by_bank: {\n iban: payment.paymentData.iban,\n },\n },\n },\n };\n }\n\n return {\n methodId: payment.methodId,\n };\n }\n\n private _isBlueSnapDirectRedirectResponse(\n response: unknown,\n ): response is BlueSnapDirectRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data.redirect_url\n );\n }\n}\n","import { BlueSnapDirectRedirectResponseProviderData } from '../types';\n\nexport default function isBlueSnapDirectRedirectResponseProviderData(\n value: unknown,\n): value is BlueSnapDirectRedirectResponseProviderData {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const partialValue: Partial = value;\n\n if (!partialValue.merchantid) {\n return false;\n }\n\n return typeof partialValue.merchantid === 'string';\n}\n","import {\n WithEcpInstrument,\n WithIdealInstrument,\n WithPayByBankInstrument,\n WithSepaInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport function isEcpInstrument(data: unknown): data is WithEcpInstrument {\n return Boolean(\n typeof data === 'object' &&\n data !== null &&\n 'accountNumber' in data &&\n 'accountType' in data &&\n 'shopperPermission' in data &&\n 'routingNumber' in data,\n );\n}\n\nexport function isIdealInstrument(paymentData: unknown): paymentData is WithIdealInstrument {\n return Boolean(typeof paymentData === 'object' && paymentData !== null && 'bic' in paymentData);\n}\n\nexport function isSepaInstrument(paymentData: unknown): paymentData is WithSepaInstrument {\n return Boolean(\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'iban' in paymentData &&\n 'firstName' in paymentData &&\n 'lastName' in paymentData &&\n 'shopperPermission' in paymentData,\n );\n}\n\nexport function isPayByBankInstrument(\n paymentData: unknown,\n): paymentData is WithPayByBankInstrument {\n return Boolean(\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'iban' in paymentData &&\n !('firstName' in paymentData) &&\n !('lastName' in paymentData) &&\n !('shopperPermission' in paymentData),\n );\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectAPMPaymentStrategy from './bluesnap-direct-apm-payment-strategy';\n\nconst createBlueSnapDirectAPMPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectAPMPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectAPMPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectAPMPaymentStrategy, [\n { gateway: 'bluesnapdirect' },\n]);\n","enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\n}\n\nexport default PaymentStatusTypes;\n","import { noop } from 'lodash';\n\nimport {\n CancellablePromise,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapV2StyleProps } from './bluesnapv2';\nimport {\n BlueSnapV2PaymentInitializeOptions,\n WithBlueSnapV2PaymentInitializeOptions,\n} from './bluesnapv2-payment-options';\n\nconst IFRAME_NAME = 'bluesnapv2_hosted_payment_page';\n\nexport default class BlueSnapV2PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapV2PaymentInitializeOptions;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions & WithBlueSnapV2PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onLoad, style } = this._initializeOptions;\n const frame = this._createIframe(IFRAME_NAME, style);\n const promise = new CancellablePromise(new Promise(noop));\n\n onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n await this._paymentIntegrationService.submitOrder(orderRequest, options);\n\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n shouldSaveInstrument: false,\n target: frame.name,\n promise: promise.promise,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async initialize(\n options?: PaymentInitializeOptions & WithBlueSnapV2PaymentInitializeOptions,\n ): Promise {\n this._initializeOptions = options && options.bluesnapv2;\n\n await Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createIframe(name: string, style?: BlueSnapV2StyleProps): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border ?? '';\n iframe.style.height = height ?? '';\n iframe.style.width = width ?? '';\n }\n\n return iframe;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapV2PaymentStrategy from './bluesnapv2-payment-strategy';\n\nconst createBluesnapV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BlueSnapV2PaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createBluesnapV2PaymentStrategy, [{ gateway: 'bluesnapv2' }]);\n","import { isObject } from 'lodash';\n\nimport { LineItemMap } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ExtraItemsData } from './extra-items-data';\n\ntype StorageFallback = Pick;\n\nconst ORDER_ITEMS_STORAGE_KEY = 'ORDER_ITEMS';\n\nfunction isExtraItemsData(itemsData: unknown): itemsData is ExtraItemsData {\n if (!isObject(itemsData)) {\n return false;\n }\n\n const hasNotExtraItems = Object.values(itemsData).some(\n (item) => !isObject(item) || !('brand' in item) || !('category' in item),\n );\n\n return Boolean(!hasNotExtraItems);\n}\n\nexport default class AnalyticsExtraItemsManager {\n constructor(private storage: StorageFallback) {}\n\n saveExtraItemsData(id: string, lineItems: LineItemMap): ExtraItemsData {\n const data = [...lineItems.physicalItems, ...lineItems.digitalItems].reduce(\n (result, item) => {\n result[item.productId] = {\n brand: item.brand ? item.brand : '',\n category: item.categoryNames ? item.categoryNames.join(', ') : '',\n };\n\n return result;\n },\n {},\n );\n\n try {\n this.storage.setItem(this.getStorageKey(id), JSON.stringify(data));\n\n return data;\n } catch (err) {\n return {};\n }\n }\n\n readExtraItemsData(id: string): ExtraItemsData | null {\n try {\n const item = this.storage.getItem(this.getStorageKey(id));\n\n if (!item) {\n return null;\n }\n\n const data: unknown = JSON.parse(item);\n\n return isExtraItemsData(data) ? data : null;\n } catch (err) {\n return null;\n }\n }\n\n clearExtraItemData(id: string): void {\n try {\n this.storage.removeItem(this.getStorageKey(id));\n } catch (err) {\n // silently ignore the failure\n }\n }\n\n private getStorageKey(id: string): string {\n return id ? `${ORDER_ITEMS_STORAGE_KEY}_${id}` : '';\n }\n}\n","import AnalyticsTrackerWindow from './analytics-tracker-window';\n\nexport function isAnalyticsTrackerWindow(window: Window): window is AnalyticsTrackerWindow {\n return Boolean(window.hasOwnProperty('analytics'));\n}\n","import { WithAccountCreation } from './payment';\n\nexport default function isWithAccountCreation(\n paymentData: unknown,\n): paymentData is WithAccountCreation {\n return (\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'shouldCreateAccount' in paymentData\n );\n}\n","import { PaymentErrorData, StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BoltError extends StandardError {\n body: { errors: PaymentErrorData[] };\n\n constructor(public errorCode: string) {\n super();\n\n this.name = 'BoltPaymentsFieldError';\n this.type = 'bolt_payments_field_error';\n this.body = { errors: [BoltError.getError(errorCode)] };\n }\n\n private static getError(errorCode: string): PaymentErrorData {\n switch (errorCode) {\n case '1000':\n case '2000':\n case '3000':\n return { code: 'invalid_number' };\n\n case '1001':\n case '2001':\n case '3001':\n return { code: 'invalid_expiry_date' };\n\n case '1002':\n case '2002':\n return { code: 'invalid_cvc' };\n\n case '1003':\n return { code: 'invalid_zip' };\n\n case '2003':\n return { code: 'incorrect_zip' };\n\n default:\n return { code: 'general_error' };\n }\n }\n}\n","import {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\nimport {\n InvalidArgumentError,\n isWithAccountCreation,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltEmbedded,\n BoltEmbeddedTokenize,\n BoltEmbededField,\n BoltPaymentMethod,\n BoltTransaction,\n} from './bolt';\nimport BoltError from './bolt-error';\nimport { WithBoltPaymentInitializeOptions } from './bolt-payment-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\nimport { isBoltPaymentData } from './is-bolt-payment-data';\n\nexport default class BoltPaymentStrategy implements PaymentStrategy {\n private boltClient?: BoltCheckout;\n private boltEmbedded?: BoltEmbedded;\n private embeddedField?: BoltEmbededField;\n private useBoltClient = false;\n private useBoltEmbedded = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBoltPaymentInitializeOptions,\n ): Promise {\n const { bolt, methodId } = options;\n const { containerId, onPaymentSelect, useBigCommerceCheckout } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!useBigCommerceCheckout) {\n // info: calling loadBoltClient method without providing any params is necessary for Bolt Full Checkout and Fraud Protection\n this.boltClient = await this.boltScriptLoader.loadBoltClient();\n\n return;\n }\n\n const paymentMethod: BoltPaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig, embeddedOneClickEnabled } =\n initializationData || {};\n const { testMode } = config;\n\n if (!publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.boltClient = await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.useBoltClient = !embeddedOneClickEnabled;\n this.useBoltEmbedded = !!embeddedOneClickEnabled;\n\n if (this.useBoltEmbedded) {\n if (!containerId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.containerId\" argument is not provided.',\n );\n }\n\n if (!onPaymentSelect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.onPaymentSelect\" argument is not provided.',\n );\n }\n\n this.boltEmbedded = await this.boltScriptLoader.loadBoltEmbedded(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.mountBoltEmbeddedField(containerId);\n onPaymentSelect(await this.hasBoltAccount());\n }\n }\n\n deinitialize(): Promise {\n this.embeddedField?.unmount();\n\n this.boltClient = undefined;\n this.boltEmbedded = undefined;\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n this.setExtraItemsForAnalytics();\n\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n let paymentPayload;\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentData || !isBoltPaymentData(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (this.useBoltClient) {\n paymentPayload = await this.getBoltClientPaymentPayload(methodId, paymentData, options);\n } else if (this.useBoltEmbedded) {\n paymentPayload = await this.getBoltEmbeddedPaymentPayload(methodId, paymentData);\n } else {\n paymentPayload = await this.getBoltFullCheckoutPaymentPayload(methodId, paymentData);\n }\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async getBoltClientPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n options?: PaymentRequestOptions,\n ): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(methodId, options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const orderToken = paymentMethod.clientToken;\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n const { shouldSaveInstrument } = paymentData;\n const boltClient = this.getBoltClientOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n\n if (!orderToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const boltTransaction: BoltTransaction = await new Promise((resolve, reject) => {\n const onSuccess = (transaction: BoltTransaction, callback: () => void) => {\n if (!transaction.reference) {\n reject(\n new PaymentMethodFailedError(\n 'Unable to proceed because transaction reference is unavailable. Please try again later.',\n ),\n );\n } else {\n resolve(transaction);\n }\n\n callback();\n };\n\n const onClose = () => {\n reject(new PaymentMethodCancelledError());\n };\n\n const callbacks = {\n success: onSuccess,\n close: onClose,\n };\n\n boltClient.configure({ orderToken }, {}, callbacks).open();\n });\n\n return {\n methodId,\n paymentData: {\n nonce: boltTransaction.reference,\n shouldSaveInstrument,\n },\n };\n }\n\n private async getBoltEmbeddedPaymentPayload(\n methodId: string,\n paymentData: WithAccountCreation,\n ): Promise {\n if (!isWithAccountCreation(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const tokenizeResult = this.validateTokenizeResultOrThrow(\n await this.embeddedField?.tokenize(),\n );\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: tokenizeResult.token,\n last_four_digits: tokenizeResult.last4,\n iin: tokenizeResult.bin,\n expiration_month: +tokenizeResult.expiration.split('-')[1],\n expiration_year: +tokenizeResult.expiration.split('-')[0],\n },\n provider_data: {\n create_account: !!paymentData.shouldCreateAccount,\n embedded_checkout: true,\n },\n },\n },\n };\n }\n\n private async getBoltFullCheckoutPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n ): Promise {\n await this.setBoltOrderId();\n\n const boltClient = this.getBoltClientOrThrow();\n const transactionReference = await boltClient.getTransactionReference();\n\n if (!transactionReference) {\n throw new PaymentMethodInvalidError();\n }\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n nonce: transactionReference,\n },\n };\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n if (!this.boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltClient;\n }\n\n private getBoltEmbeddedOrThrow() {\n if (!this.boltEmbedded) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltEmbedded;\n }\n\n private async hasBoltAccount(): Promise {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const email = customer?.email || billingAddress?.email || '';\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private async setBoltOrderId() {\n const order = this.paymentIntegrationService.getState().getOrderOrThrow();\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n await boltClient.setOrderId(order.orderId);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private mountBoltEmbeddedField(containerId: string) {\n const boltEmbedded = this.getBoltEmbeddedOrThrow();\n const styles = { backgroundColor: '#fff' };\n const embeddedField = boltEmbedded.create('payment_field', {\n styles,\n renderSeparateFields: true,\n });\n\n embeddedField.mount(`#${containerId}`);\n\n this.embeddedField = embeddedField;\n }\n\n private validateTokenizeResultOrThrow(\n tokenizeResult?: BoltEmbeddedTokenize | Error,\n ): BoltEmbeddedTokenize {\n if (!tokenizeResult) {\n throw new PaymentMethodInvalidError();\n }\n\n if (tokenizeResult instanceof Error) {\n throw new BoltError(tokenizeResult.message);\n }\n\n const { token, last4, bin, expiration } = tokenizeResult;\n const lastFourDigits = +last4;\n const iin = +bin;\n const expirationMonth = +`${expiration}`.split('-')[1];\n const expirationYear = +`${expiration}`.split('-')[0];\n\n if (\n !token ||\n Number.isNaN(lastFourDigits) ||\n Number.isNaN(iin) ||\n Number.isNaN(expirationMonth) ||\n Number.isNaN(expirationYear)\n ) {\n throw new PaymentArgumentInvalidError();\n }\n\n return tokenizeResult;\n }\n\n private setExtraItemsForAnalytics() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n const cart = state.getCartOrThrow();\n\n if (storeConfig.checkoutSettings.isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n const { id, lineItems } = cart;\n\n this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n }\n }\n}\n","import { isObject } from 'lodash';\n\nimport { isWithAccountCreation } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltPaymentData } from './bolt';\n\nexport function isBoltPaymentData(paymentData: unknown): paymentData is BoltPaymentData {\n return Boolean(\n isObject(paymentData) &&\n ('shouldSaveInstrument' in paymentData ||\n 'nonce' in paymentData ||\n isWithAccountCreation(paymentData)),\n );\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\nimport localStorageFallback from 'local-storage-fallback';\n\nimport { AnalyticsExtraItemsManager } from '@bigcommerce/checkout-sdk/analytics';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltPaymentStrategy from './bolt-payment-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltPaymentStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n new AnalyticsExtraItemsManager(localStorageFallback),\n );\n};\n\nexport default toResolvableModule(createBoltPaymentStrategy, [{ id: 'bolt' }]);\n","import {\n PaymentInstrumentPayload,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isUsBankAccountInstrumentLike(\n instrument?: PaymentInstrumentPayload,\n): instrument is WithBankAccountInstrument {\n if (!instrument) {\n return false;\n }\n\n return (\n 'accountNumber' in instrument &&\n 'routingNumber' in instrument &&\n 'ownershipType' in instrument &&\n 'accountType' in instrument\n );\n}\n","import {\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeUsBankAccount,\n BraintreeUsBankAccountDetails,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isUsBankAccountInstrumentLike from '../is-us-bank-account-instrument-like';\n\nimport { WithBraintreeAchPaymentInitializeOptions } from './braintree-ach-initialize-options';\n\nexport default class BraintreeAchPaymentStrategy implements PaymentStrategy {\n private usBankAccount?: BraintreeUsBankAccount;\n private getMandateText?: () => string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeAchPaymentInitializeOptions,\n ): Promise {\n const { methodId, braintreeach } = options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.getMandateText = braintreeach?.getMandateText;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n try {\n this.usBankAccount = await this.braintreeSdk.getUsBankAccount();\n } catch (error) {\n this.handleBraintreeError(error);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const isSubmittingWithVaultingInstrument = isVaultedInstrument(payment.paymentData || {});\n\n const nonce = isSubmittingWithVaultingInstrument\n ? await this.tokenizePaymentForVaultedInstrument(payment)\n : await this.tokenizePayment(payment);\n\n const submitPaymentPayload = isSubmittingWithVaultingInstrument\n ? await this.preparePaymentDataForVaultedInstrument(nonce, payment)\n : await this.preparePaymentData(nonce, payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n\n return Promise.resolve();\n }\n\n private async tokenizePayment({ paymentData }: OrderPaymentRequestBody): Promise {\n const usBankAccount = this.getUsBankAccountOrThrow();\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const mandateText = isVaultedInstrument(paymentData)\n ? 'The data are used for stored instrument verification'\n : typeof this.getMandateText === 'function' && this.getMandateText();\n\n if (!mandateText) {\n throw new InvalidArgumentError(\n 'Unable to proceed because getMandateText is not provided or returned undefined value.',\n );\n }\n\n try {\n const { nonce } = await usBankAccount.tokenize({\n bankDetails: this.getBankDetails(paymentData),\n mandateText,\n });\n\n return nonce;\n } catch (error) {\n this.handleBraintreeError(error);\n }\n }\n\n private async tokenizePaymentForVaultedInstrument(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n const state = this.paymentIntegrationService.getState();\n const { config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!config.isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n const shouldVerifyVaultingInstrument = isUsBankAccountInstrumentLike(paymentData);\n\n return shouldVerifyVaultingInstrument ? this.tokenizePayment(payment) : null;\n }\n\n private async preparePaymentData(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument, routingNumber, accountNumber } =\n paymentData;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId: deviceData,\n shouldSetAsDefaultInstrument,\n shouldSaveInstrument,\n formattedPayload: {\n tokenized_bank_account: {\n issuer: routingNumber,\n masked_account_number: accountNumber.substr(-4),\n token: nonce,\n },\n },\n },\n };\n }\n\n private async preparePaymentDataForVaultedInstrument(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n if (!isVaultedInstrument(paymentData) || !isHostedInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { instrumentId, shouldSetAsDefaultInstrument } = paymentData;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId: deviceData,\n instrumentId,\n shouldSetAsDefaultInstrument,\n ...(nonce && { nonce }),\n },\n };\n }\n\n private getBankDetails(paymentData: WithBankAccountInstrument): BraintreeUsBankAccountDetails {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const ownershipType = paymentData.ownershipType.toLowerCase();\n const accountType = paymentData.accountType.toLowerCase();\n\n return {\n accountNumber: paymentData.accountNumber,\n routingNumber: paymentData.routingNumber,\n ownershipType,\n ...(ownershipType === 'personal'\n ? {\n firstName: paymentData.firstName,\n lastName: paymentData.lastName,\n }\n : {\n businessName: paymentData.businessName,\n }),\n accountType,\n billingAddress: {\n streetAddress: billingAddress.address1,\n extendedAddress: billingAddress.address2,\n locality: billingAddress.city,\n region: billingAddress.stateOrProvinceCode,\n postalCode: billingAddress.postalCode,\n },\n };\n }\n\n private getUsBankAccountOrThrow(): BraintreeUsBankAccount {\n if (!this.usBankAccount) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.usBankAccount;\n }\n\n private handleBraintreeError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n}\n","import { createBraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeAchPaymentStrategy from './braintree-ach-payment-strategy';\n\nconst createBraintreeAchPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BraintreeAchPaymentStrategy(paymentIntegrationService, createBraintreeSdk());\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\n\nconst createBraintreeSdk = () => {\n const braintreeScriptLoader = new BraintreeScriptLoader(getScriptLoader(), window);\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import getOverlayStyle from './overlay-style';\n\nexport interface OverlayOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n hasCloseButton?: boolean;\n innerHtml?: HTMLElement | DocumentFragment;\n}\n\nexport interface OverlayShowOptions {\n onClick?(event: MouseEvent): void;\n onClickClose?(event: MouseEvent): void;\n}\n\nexport interface Elements {\n element: HTMLElement;\n mainElement: HTMLElement;\n closeElement?: HTMLElement;\n}\n\nexport default class Overlay {\n private _element: HTMLElement;\n private _mainElement: HTMLElement;\n private _closeElement?: HTMLElement;\n private _unregisterClick?: () => void;\n\n constructor(options?: OverlayOptions) {\n const { element, closeElement, mainElement } = this._createElements(options);\n\n this._element = element;\n this._closeElement = closeElement;\n this._mainElement = mainElement;\n }\n\n show(options?: OverlayShowOptions): void {\n if (this._mainElement.parentElement) {\n return;\n }\n\n this._registerClick(options);\n\n document.body.appendChild(this._mainElement);\n\n // Fade In\n setTimeout(() => (this._element.style.opacity = '1'));\n }\n\n remove(): void {\n if (!this._mainElement.parentElement) {\n return;\n }\n\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n this._removeAfterTransition();\n\n setTimeout(() => (this._element.style.opacity = '0'));\n }\n\n private _createElements(options?: OverlayOptions): Elements {\n const element = document.createElement('div');\n const {\n background = 'rgba(0, 0, 0, 0.8)',\n id = 'checkoutOverlay',\n transitionDuration = 400,\n hasCloseButton = false,\n innerHtml = null,\n } = options || {};\n let mainElement = element;\n let closeElement: HTMLElement | undefined;\n let classLayout: string | undefined;\n let classClose: string | undefined;\n let classOverlayText: string | undefined;\n\n if (id) {\n element.id = id;\n }\n\n if (innerHtml) {\n const overlayText = document.createElement('div');\n\n classOverlayText = `${id}--overlayText`;\n overlayText.className = classOverlayText;\n overlayText.appendChild(innerHtml);\n\n element.appendChild(overlayText);\n }\n\n if (hasCloseButton) {\n classClose = `${id}--close`;\n closeElement = document.createElement('div');\n closeElement.className = classClose;\n\n classLayout = `${id}--layout`;\n mainElement = document.createElement('div');\n mainElement.className = classLayout;\n\n mainElement.appendChild(element);\n mainElement.appendChild(closeElement);\n }\n\n mainElement.appendChild(\n getOverlayStyle({\n id,\n background,\n transitionDuration,\n classLayout,\n classOverlayText,\n classClose,\n }),\n );\n\n return { element, closeElement, mainElement };\n }\n\n private _addEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n if (!element || !onClick) {\n return;\n }\n\n element.addEventListener('click', onClick);\n }\n\n private _removeEventListener(\n element?: HTMLElement,\n onClick?: (event: MouseEvent) => void,\n ): void {\n if (!element || !onClick) {\n return;\n }\n\n element.removeEventListener('click', onClick);\n }\n\n private _registerClick(options?: OverlayShowOptions): void {\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n if (options) {\n const { onClick, onClickClose } = options;\n\n this._addEventListener(this._element, onClick);\n this._addEventListener(this._closeElement, onClickClose);\n\n this._unregisterClick = () => {\n this._removeEventListener(this._element, onClick);\n this._removeEventListener(this._closeElement, onClickClose);\n this._unregisterClick = undefined;\n };\n }\n }\n\n private _removeAfterTransition(): void {\n const handleTransition: (event: Event) => void = (event) => {\n // NOTE: `event` is not correctly typed in this version of TS\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n if ((event as TransitionEvent).propertyName !== 'opacity') {\n return;\n }\n\n if (this._mainElement.parentElement) {\n this._mainElement.remove();\n }\n\n this._element.removeEventListener('transitionend', handleTransition);\n };\n\n this._element.addEventListener('transitionend', handleTransition);\n }\n}\n","interface OverlayStyleOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n classLayout?: string;\n classOverlayText?: string;\n classClose?: string;\n}\n\nexport default function getOverlayStyle(options: OverlayStyleOptions): HTMLElement {\n const { id, background, transitionDuration, classLayout, classOverlayText, classClose } =\n options;\n const styles = document.createElement('style');\n const addClassLayout = classLayout ? `, .${classLayout}` : '';\n\n styles.id = `${id}--styles`;\n styles.type = 'text/css';\n styles.innerText = `\n #${id}${addClassLayout} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${id} {\n transition: opacity ${transitionDuration}ms ease-out;\n background: ${background};\n opacity: 0;\n }\n `;\n\n if (classOverlayText) {\n styles.innerText += `\n #${id} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${id} .${classOverlayText} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `;\n }\n\n if (classClose) {\n styles.innerText += `\n #${id} {\n opacity: 1;\n }\n .${classLayout} .${classClose} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${classLayout} .${classClose}::after, .${classLayout} .${classClose}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${classLayout} .${classClose}::after {\n transform: rotate(-45deg);\n }\n .${classLayout} .${classClose}::before {\n transform: rotate(45deg);\n }\n `;\n }\n\n return styles;\n}\n","import {\n LoadingIndicatorContainerStyles,\n LoadingIndicatorStyles,\n} from './loading-indicator-styles';\n\nconst DEFAULT_STYLES: LoadingIndicatorStyles = {\n size: 70,\n color: '#d9d9d9',\n backgroundColor: '#ffffff',\n};\n\nconst ROTATION_ANIMATION = 'embedded-checkout-loading-indicator-rotation';\n\ninterface LoadingIndicatorOptions {\n styles?: LoadingIndicatorStyles;\n containerStyles?: LoadingIndicatorContainerStyles;\n}\n\nexport default class LoadingIndicator {\n private container: HTMLElement;\n private indicator: HTMLElement;\n private styles: LoadingIndicatorStyles;\n private containerStyles: LoadingIndicatorContainerStyles;\n\n constructor(options?: LoadingIndicatorOptions) {\n this.styles = { ...DEFAULT_STYLES, ...(options && options.styles) };\n this.containerStyles = { ...(options && options.containerStyles) };\n\n this.defineAnimation();\n\n this.container = this.buildContainer();\n this.indicator = this.buildIndicator();\n\n this.container.appendChild(this.indicator);\n }\n\n show(parentId?: string): void {\n if (parentId) {\n const parent = document.getElementById(parentId);\n\n if (!parent) {\n throw new Error(\n 'Unable to attach the loading indicator because the parent ID is not valid.',\n );\n }\n\n parent.appendChild(this.container);\n }\n\n this.container.style.visibility = 'visible';\n this.container.style.opacity = '1';\n }\n\n hide(): void {\n const handleTransitionEnd = () => {\n this.container.style.visibility = 'hidden';\n\n this.container.removeEventListener('transitionend', handleTransitionEnd);\n };\n\n this.container.addEventListener('transitionend', handleTransitionEnd);\n\n this.container.style.opacity = '0';\n }\n\n private buildContainer(): HTMLElement {\n const container = document.createElement('div');\n\n container.style.display = 'block';\n container.style.bottom = '0';\n container.style.left = '0';\n container.style.height = '100%';\n container.style.width = '100%';\n container.style.position = 'absolute';\n container.style.right = '0';\n container.style.top = '0';\n container.style.transition = 'all 250ms ease-out';\n container.style.opacity = '0';\n\n this.setStyleAttribute(container, this.containerStyles);\n\n return container;\n }\n\n private buildIndicator(): HTMLElement {\n const indicator = document.createElement('div');\n\n indicator.style.display = 'block';\n indicator.style.width = `${this.styles.size}px`;\n indicator.style.height = `${this.styles.size}px`;\n indicator.style.borderRadius = `${this.styles.size}px`;\n indicator.style.border = 'solid 1px';\n indicator.style.borderColor = `${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`;\n indicator.style.margin = '0 auto';\n indicator.style.position = 'absolute';\n indicator.style.left = '0';\n indicator.style.right = '0';\n indicator.style.top = '50%';\n indicator.style.transform = 'translateY(-50%) rotate(0deg)';\n indicator.style.transformStyle = 'preserve-3d';\n indicator.style.animation = `${ROTATION_ANIMATION} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`;\n\n return indicator;\n }\n\n private setStyleAttribute(element: HTMLElement, attrs: { [key: string]: string }): void {\n Object.keys(attrs).forEach((k) => {\n element.style.setProperty(k, attrs[k]);\n });\n }\n\n private defineAnimation(): void {\n // In order to define CSS animation, we need to insert a stylesheet into the host frame.\n // We only have to do it once.\n if (document.getElementById(ROTATION_ANIMATION)) {\n return;\n }\n\n const style = document.createElement('style');\n\n style.id = ROTATION_ANIMATION;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n document.head?.appendChild(style);\n\n if (style.sheet instanceof CSSStyleSheet) {\n // We need to provide the 2nd parameter for IE11, even though it is\n // 0 by default for all other browsers.\n style.sheet.insertRule(\n `\n @keyframes ${ROTATION_ANIMATION} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,\n 0,\n );\n }\n }\n}\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { BraintreeError } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function isBraintreeError(\n error: BraintreeError | Error | unknown,\n): error is BraintreeError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n (error as BraintreeError).name === 'BraintreeError'\n );\n}\n","import { BraintreeShippingAddressOverride } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","import {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n PaypalAuthorizeData,\n PaypalButtonRender,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isHostedVaultedInstrument,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n PaypalInstrument,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport isBraintreeError from '../is-braintree-error';\nimport isBraintreePaypalProviderError from '../is-braintree-paypal-provider-error';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport {\n BraintreePaypalPaymentInitializeOptions,\n WithBraintreePaypalPaymentInitializeOptions,\n} from './braintree-paypal-payment-initialize-options';\n\nexport default class BraintreePaypalPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n private braintreeHostWindow: BraintreeHostWindow = window;\n private braintree?: BraintreePaypalPaymentInitializeOptions;\n private braintreeTokenizePayload?: BraintreeTokenizePayload;\n private paypalButtonRender?: PaypalButtonRender;\n private loadingIndicatorContainer?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n this.braintree = braintreeOptions;\n\n if (!this.paymentMethod || !this.paymentMethod.nonce) {\n this.paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n }\n\n if (this.paymentMethod.clientToken && braintreeOptions?.bannerContainerId) {\n await this.loadPaypal();\n\n return this.loadPaypalCheckoutInstance();\n }\n\n if (this.paymentMethod.clientToken) {\n return this.loadPaypal();\n }\n\n const state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (braintreeOptions?.bannerContainerId) {\n return this.loadPaypalCheckoutInstance();\n }\n\n if (!this.paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this.loadPaypal();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n const { onError } = this.braintree || {};\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const shouldHandleInstrumentDeclinedError =\n features && features['PAYPAL-3521.handling_declined_error_braintree'];\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this.preparePaymentData(payment, order.useStoreCredit);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentData);\n } catch (error) {\n if (this.isProviderError(error) && shouldHandleInstrumentDeclinedError) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance();\n\n await new Promise((_resolve, reject) => {\n if (onError && typeof onError === 'function') {\n onError(new Error('INSTRUMENT_DECLINED'));\n }\n\n reject();\n });\n }\n\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.braintreeTokenizePayload = undefined;\n\n this.paypalButtonRender?.close();\n\n return this.braintreeIntegrationService.teardown();\n }\n\n private async preparePaymentData(\n payment: OrderPaymentRequestBody,\n useStoreCredit?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n const grandTotal = state.getOutstandingBalance(useStoreCredit);\n const config = state.getStoreConfig();\n\n if (!grandTotal) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this.paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n currency,\n storeProfile: { storeLanguage },\n } = config;\n const {\n nonce,\n config: { isVaultingEnabled },\n } = this.paymentMethod;\n const { methodId, paymentData = {} } = payment;\n\n const token = this.braintreeTokenizePayload?.nonce || nonce;\n\n if (token) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n this.paymentMethod = state.getPaymentMethod(methodId);\n\n return {\n ...payment,\n paymentData: this.formattedPayload(token),\n };\n }\n\n if (isVaultedInstrument(paymentData) || isHostedVaultedInstrument(paymentData)) {\n if (!isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n return Promise.resolve(payment);\n }\n\n if (!isHostedInstrumentLike(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = paymentData;\n\n if (shouldSaveInstrument && !isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but shouldSaveInstrument is set to true',\n );\n }\n\n const shippingAddress = state.getShippingAddress();\n\n const shippingAddressOverride = shippingAddress\n ? mapToBraintreeShippingAddressOverride(shippingAddress)\n : undefined;\n\n return Promise.all([\n this.braintreeIntegrationService.paypal({\n amount: grandTotal,\n locale: storeLanguage,\n currency: currency.code,\n offerCredit: this.paymentMethod.id === 'braintreepaypalcredit',\n shippingAddressOverride,\n shouldSaveInstrument: shouldSaveInstrument || false,\n shippingAddressEditable: false,\n }),\n this.braintreeIntegrationService.getSessionId(),\n ]).then(([{ nonce, details } = {} as any, sessionId]) => ({\n ...payment,\n paymentData: this.formattedPayload(\n nonce,\n details && details.email,\n sessionId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n ),\n }));\n }\n\n private formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n vaultPaymentInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: vaultPaymentInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private async loadPaypalCheckoutInstance() {\n const { clientToken, initializationData } = this.paymentMethod || {};\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n\n const currencyCode = this.paymentIntegrationService.getState().getCartOrThrow()\n .currency.code;\n\n const paypalCheckoutConfig: Partial = {\n currency: currencyCode,\n intent: initializationData?.intent,\n isCreditEnabled: initializationData?.isCreditEnabled,\n };\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (initializationData?.enableCheckoutPaywallBanner) {\n this.renderPayPalMessages();\n }\n\n this.renderPayPalButton(braintreePaypalCheckout);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalButton(braintreePaypalCheckout: BraintreePaypalCheckout) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } =\n this.braintree || {};\n\n if (!containerId) {\n return;\n }\n\n if (!this.paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.loadingIndicatorContainer = containerId.split('#')[1];\n\n const {\n id,\n config: { testMode },\n } = this.paymentMethod;\n\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n this.paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n onClick: () => {\n this.toggleLoadingIndicator(true);\n },\n createOrder: () => this.setupPayment(braintreePaypalCheckout, id, onPaymentError),\n onApprove: async (authorizeData: PaypalAuthorizeData) => {\n this.braintreeTokenizePayload = await this.tokenizePaymentOrThrow(\n authorizeData,\n braintreePaypalCheckout,\n );\n\n if (submitForm && typeof submitForm === 'function') {\n submitForm();\n }\n },\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n },\n onError: (error: Error) => {\n this.toggleLoadingIndicator(false);\n\n onError?.(error);\n },\n });\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n if (this.paypalButtonRender.isEligible()) {\n this.paypalButtonRender.render(`${containerId}`);\n }\n } else {\n this.removeElement(containerId.split('#')[1]);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n method: string,\n onPaymentError: BraintreePaypalPaymentInitializeOptions['onPaymentError'],\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n try {\n const customer = state.getCustomer();\n\n const paymentMethod: PaymentMethod = state.getPaymentMethodOrThrow(method);\n\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currencyCode = state.getStoreConfigOrThrow().currency.code;\n\n const shippingAddress = state.getShippingAddress();\n\n const address = shippingAddress || customer?.addresses[0];\n\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData.intent,\n });\n } catch (error) {\n if (onPaymentError && (isBraintreeError(error) || error instanceof StandardError)) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePaymentOrThrow(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n return await braintreePaypalCheckout.tokenizePayment(authorizeData);\n } catch (error) {\n if (onError && (isBraintreeError(error) || error instanceof StandardError)) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private renderPayPalMessages() {\n const { bannerContainerId } = this.braintree || {};\n\n if (\n this.braintreeHostWindow.paypal &&\n bannerContainerId &&\n Boolean(document.getElementById(bannerContainerId))\n ) {\n const state = this.paymentIntegrationService.getState();\n const checkout = state.getCheckout();\n const billingAddress = state.getBillingAddressOrThrow();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: checkout.subtotal,\n buyerCountry: billingAddress.countryCode,\n placement: 'payment',\n style: {\n layout: 'text',\n logo: {\n type: 'inline',\n },\n },\n })\n .render(`#${bannerContainerId}`);\n }\n }\n\n private async loadPaypal() {\n const { clientToken, initializationData } = this.paymentMethod || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n\n await this.braintreeIntegrationService.getPaypal();\n } catch (error) {\n this.handleError(error);\n }\n\n return Promise.resolve();\n }\n\n private handleError(error: BraintreeError | Error | unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBraintreePaypalProviderError(error)) {\n const paypalProviderError = error?.errors?.filter((e) => e.provider_error) || [];\n\n return paypalProviderError[0]?.provider_error?.code === '2046';\n }\n\n return false;\n }\n\n private removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","export interface ProviderError extends Error {\n errors?: ErrorElement[];\n status?: string;\n three_ds_result?: {\n acs_url: unknown;\n payer_auth_request: unknown;\n merchant_data: unknown;\n callback_url: unknown;\n };\n}\n\nexport interface ErrorElement {\n code: string;\n message: string;\n provider_error?: {\n code: string;\n };\n}\n\nexport default function isBraintreePaypalProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator, Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../braintree-paypal-constants';\n\nimport BraintreePaypalPaymentStrategy from './braintree-paypal-payment-strategy';\n\nconst createBraintreePaypalPaymentStrategy: PaymentStrategyFactory<\n BraintreePaypalPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const overlay = new Overlay();\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n overlay,\n );\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalPaymentStrategy, [\n { id: 'braintreepaypal' },\n { id: 'braintreepaypalcredit' },\n]);\n","import {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeRedirectError,\n BraintreeSdk,\n NonInstantLocalPaymentMethods,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nexport default class BraintreeLocalMethodsPaymentStrategy implements PaymentStrategy {\n private braintreelocalmethods?: BraintreeLocalMethodsPaymentInitializeOptions;\n private braintreeLocalPayment?: BraintreeLocalPayment;\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!braintreelocalmethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreelocalmethods\" argument is not provided.`,\n );\n }\n\n this.braintreelocalmethods = braintreelocalmethods;\n this.loadingIndicatorContainer = braintreelocalmethods.container.split('#')[1];\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(gatewayId);\n const { clientToken, config, initializationData } = paymentMethod;\n\n this.isLPMsUpdateExperimentEnabled =\n state.getStoreConfigOrThrow().checkoutSettings.features[\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms'\n ] || false;\n\n if (!clientToken || !initializationData || !config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeSdk.initialize(clientToken);\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n this.braintreeLocalPayment = await this.braintreeSdk.getBraintreeLocalPayment(\n config.merchantId,\n );\n }\n } catch (error: unknown) {\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.toggleLoadingIndicator(false);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n this.toggleLoadingIndicator(true);\n\n if (this.isNonInstantPaymentMethod(methodId)) {\n await this.executeWithNotInstantLPM(methodId);\n } else {\n await this.executeWithInstantLPM(methodId, order, options);\n }\n }\n\n private async executeWithNotInstantLPM(methodId: string): Promise {\n try {\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n\n await this.paymentIntegrationService.submitOrder();\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n },\n },\n });\n } catch (error: unknown) {\n if (this.isBraintreeRedirectError(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise((_, reject) => {\n window.location.replace(redirectUrl);\n\n this.toggleLoadingIndicator(false);\n\n reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(error);\n }\n }\n\n private async executeWithInstantLPM(\n methodId: string,\n order: Omit,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!this.braintreeLocalPayment) {\n throw new PaymentMethodInvalidError();\n }\n\n await new Promise((resolve, reject): void => {\n this.braintreeLocalPayment?.startPayment(\n this.getInstantLPMConfig(methodId, order, options),\n this.getInstantLPMCallback(resolve, reject, methodId, order, options),\n );\n });\n }\n\n private async getLPMsBasicPaymentData(): Promise {\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n\n return { deviceSessionId: deviceData };\n }\n\n private getInstantLPMConfig(\n methodId: string,\n order: Omit,\n options?: RequestOptions,\n ): BraintreeLocalPaymentConfig {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billing = state.getBillingAddressOrThrow();\n const { firstName, lastName, countryCode } = billing;\n const { currency, email, lineItems } = cart;\n const isShippingRequired = lineItems.physicalItems.length > 0;\n const grandTotal = state.getCheckoutOrThrow().outstandingBalance;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: 'url-placeholder',\n buttonText: 'button placeholder',\n },\n currencyCode: currency.code,\n shippingAddressRequired: isShippingRequired,\n email,\n givenName: firstName,\n surname: lastName,\n address: {\n countryCode,\n },\n onPaymentStart: async (data: BraintreeLPMPaymentStartData, start: () => void) => {\n if (!this.isLPMsUpdateExperimentEnabled) {\n this.orderId = data.paymentId;\n\n start();\n\n return;\n }\n\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n const paymentData = {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n [`${methodId}_account`]: {\n order_id: data.paymentId,\n },\n },\n };\n\n try {\n // Submit order and payment should be performed to pass order_id to the backend\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n });\n } catch (error: unknown) {\n if (\n this.isBraintreeOrderSavedResponse(error) &&\n error.body.additional_action_required.data.order_id_saved_successfully\n ) {\n // Start method call initiates the popup\n start();\n\n return;\n }\n\n throw error;\n }\n },\n };\n }\n\n private getInstantLPMCallback(\n resolve: (value: unknown) => void,\n reject: (reason?: unknown) => void,\n methodId: string,\n order: Omit,\n options?: RequestOptions,\n ) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n\n return async (\n startPaymentError: BraintreeLPMStartPaymentError | undefined,\n payloadData: BraintreeLocalPaymentsPayload,\n ) => {\n if (startPaymentError) {\n if (startPaymentError.code === 'LOCAL_PAYMENT_WINDOW_CLOSED') {\n this.toggleLoadingIndicator(false);\n\n return reject();\n }\n\n this.toggleLoadingIndicator(false);\n\n return reject(new PaymentMethodInvalidError());\n }\n\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n const paymentData = {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n [`${methodId}_account`]: {\n email: cart.email,\n token: payloadData.nonce,\n ...(!this.isLPMsUpdateExperimentEnabled ? { order_id: this.orderId } : {}),\n },\n },\n };\n\n try {\n if (!this.isLPMsUpdateExperimentEnabled) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n });\n\n return resolve(undefined);\n } catch (error: unknown) {\n this.handleError(error);\n\n return reject(error);\n }\n };\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n private handleError(error: unknown) {\n const { onError } = this.braintreelocalmethods || {};\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantLocalPaymentMethods;\n }\n\n private isBraintreeRedirectError(error: unknown): error is BraintreeRedirectError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n\n const { body }: Partial = error;\n\n if (!body) {\n return false;\n }\n\n return !!body.additional_action_required?.data.redirect_url;\n }\n\n private isBraintreeOrderSavedResponse(\n response: unknown,\n ): response is BraintreeOrderSavedResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const { body }: Partial = response;\n\n if (!body) {\n return false;\n }\n\n return body.additional_action_required?.data.hasOwnProperty('order_id_saved_successfully');\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n};\n\nexport default toResolvableModule(createBraintreeLocalMethodsPaymentStrategy, [\n { gateway: 'braintreelocalmethods' },\n]);\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBraintreeAcceleratedCheckoutCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CardInstrument,\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport { WithBraintreeFastlanePaymentInitializeOptions } from './braintree-fastlane-payment-initialize-options';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nexport default class BraintreeFastlanePaymentStrategy implements PaymentStrategy {\n private braintreeCardComponent?: BraintreeFastlaneCardComponent;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private browserStorage: BrowserStorage,\n ) {}\n\n /**\n *\n * Default methods\n *\n */\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, braintreefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreefastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane\" argument is not provided.',\n );\n }\n\n if (!braintreefastlane.onInit || typeof braintreefastlane.onInit !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (!braintreefastlane.onChange || typeof braintreefastlane.onChange !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane.onChange\" argument is not provided or it is not a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, isFastlaneStylingEnabled } = paymentMethod.initializationData || {};\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\n\n if (!clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStyleSettings,\n braintreefastlane.styles,\n );\n\n await this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(\n methodId,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow();\n }\n\n await this.initializeCardComponent();\n\n braintreefastlane.onInit((container) => this.renderBraintreeCardComponent(container));\n braintreefastlane.onChange(() => this.handleBraintreeStoredInstrumentChange(methodId));\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.browserStorage.removeItem('sessionId');\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.braintreeCardComponent = undefined;\n\n return Promise.resolve();\n }\n\n /**\n *\n * Braintree Fastlane Component rendering method\n *\n */\n private async initializeCardComponent() {\n const state = this.paymentIntegrationService.getState();\n const { phone, firstName, lastName } = state.getBillingAddressOrThrow();\n const fullName = `${firstName} ${lastName}`;\n\n const cardComponentOptions: BraintreeFastlaneCardComponentOptions = {\n styles: {},\n fields: {\n cardholderName: {\n prefill: fullName,\n enabled: true,\n },\n ...(phone && {\n phoneNumber: {\n prefill: phone,\n },\n }),\n },\n };\n\n const paypalPaymentComponent =\n this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();\n\n this.braintreeCardComponent = await paypalPaymentComponent(cardComponentOptions);\n }\n\n private renderBraintreeCardComponent(container?: string) {\n const braintreeCardComponent = this.getBraintreeCardComponentOrThrow();\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n braintreeCardComponent.render(container);\n }\n\n /**\n *\n * Payment Payload preparation methods\n *\n */\n private async preparePaymentPayload(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`;\n\n const paypalInstrument = this.getPayPalInstruments()[0];\n\n const deviceSessionId = await this.braintreeFastlaneUtils.getDeviceSessionId();\n\n if (paypalInstrument) {\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const { id } = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: id,\n },\n };\n }\n\n /**\n *\n * Mapper methods\n *\n */\n private mapToPayPalAddress(address?: Address): BraintreeFastlaneAddress {\n return {\n streetAddress: address?.address1 || '',\n locality: address?.city || '',\n region: address?.stateOrProvinceCode || address?.stateOrProvince || '',\n postalCode: address?.postalCode || '',\n countryCodeAlpha2: address?.countryCode || '',\n };\n }\n\n /**\n *\n * Other methods\n *\n */\n private shouldRunAuthenticationFlow(): boolean {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const paypalFastlaneSessionId = this.browserStorage.getItem('sessionId');\n\n if (\n !customer.isGuest ||\n braintreePaymentProviderCustomer?.authenticationState ===\n BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return (\n !braintreePaymentProviderCustomer?.authenticationState &&\n paypalFastlaneSessionId === cart.id\n );\n }\n\n private getBraintreeCardComponentOrThrow() {\n if (!this.braintreeCardComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeCardComponent;\n }\n\n private getPayPalInstruments(): CardInstrument[] {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return braintreePaymentProviderCustomer.instruments || [];\n }\n\n /**\n *\n * Braintree Fastlane instrument change\n *\n */\n private async handleBraintreeStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow();\n\n const { selectionChanged, selectedCard } = await paypalAxoSdk.profile.showCardSelector();\n\n if (selectionChanged) {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const braintreeFastlaneCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const selectedInstruments = this.braintreeFastlaneUtils.mapPayPalToBcInstrument(\n methodId,\n [selectedCard],\n );\n\n if (selectedInstruments && selectedInstruments.length > 0) {\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n ...braintreeFastlaneCustomer,\n instruments: [...selectedInstruments],\n });\n\n return selectedInstruments[0];\n }\n }\n\n return undefined;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport BraintreeFastlanePaymentStrategy from './braintree-fastlane-payment-strategy';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nconst createBraintreeFastlanePaymentStrategy: PaymentStrategyFactory<\n BraintreeFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n const browserStorage = new BrowserStorage('paypalFastlane');\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n browserStorage,\n );\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n browserStorage,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { isNil, values } from 'lodash';\n\nimport {\n HostedForm,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCreditCardPaymentInitializeOptions } from './credit-card-payment-initialize-options';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(protected _paymentIntegrationService: PaymentIntegrationService) {}\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n initialize(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve();\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const state = this._paymentIntegrationService.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n state.getStoreConfigOrThrow();\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._paymentIntegrationService.createHostedForm(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return Promise.resolve();\n });\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await form.validate().then(() => form.submit(payment));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface AdditionalActionRequired {\n type: AdditionalActionType;\n data: AdditionalRedirectData;\n}\n\nexport interface AdditionalRedirectData {\n redirect_url: string;\n transaction_id?: string;\n}\n\nexport enum AdditionalActionType {\n OffsiteRedirect = 'offsite_redirect',\n}\n\nexport function getCheckoutcom(): PaymentMethod {\n return {\n id: 'checkoutcom',\n logoUrl: '',\n method: 'checkoutcom',\n supportedCards: [],\n config: {\n displayName: 'Checkout.com',\n merchantId: '',\n testMode: true,\n },\n initializationData: {\n checkoutcomkey: 'key',\n },\n type: 'PAYMENT_TYPE_API',\n clientToken: 'clientToken',\n };\n}\n\nexport interface WithDocumentInstrument {\n ccDocument: string;\n}\n\nexport interface WithCheckoutcomSEPAInstrument {\n iban: string;\n bic: string;\n}\n\nexport interface WithCheckoutcomFawryInstrument {\n customerMobile: string;\n customerEmail: string;\n}\n","import { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, AdditionalActionType } from './checkoutcom';\n\nexport default class CheckoutComCustomPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(protected paymentIntegrationService: PaymentIntegrationService) {\n super(paymentIntegrationService);\n }\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this.paymentIntegrationService.submitOrder(order, options);\n await form.submit(payment);\n } catch (error) {\n return this._processResponse(error);\n }\n\n this.paymentIntegrationService.loadCurrentOrder();\n }\n\n protected _processResponse(error: unknown): Promise {\n if (!isRequestError(error)) {\n return Promise.reject(error);\n }\n\n const additionalActionRequired: AdditionalActionRequired =\n error.body.additional_action_required;\n\n // TODO validate all possible responses and perform respective additional actions\n if (\n additionalActionRequired &&\n additionalActionRequired.type === AdditionalActionType.OffsiteRedirect\n ) {\n return this._performRedirect(additionalActionRequired);\n }\n\n return Promise.reject(error);\n }\n\n private _performRedirect(additionalActionRequired: AdditionalActionRequired): Promise {\n return new Promise(() => {\n window.location.replace(additionalActionRequired.data.redirect_url);\n });\n }\n}\n","import {\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCheckoutcomFawryInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_FAWRY_PAYMENT_METHOD = 'fawry';\n\nexport default class CheckoutComFawryPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomFawryInstrument | undefined {\n if (\n CHECKOUTCOM_FAWRY_PAYMENT_METHOD === methodId &&\n 'customerMobile' in paymentData &&\n 'customerEmail' in paymentData\n ) {\n const fawryPaymentData = paymentData as {\n customerMobile: string;\n customerEmail: string;\n };\n\n return {\n customerMobile: fawryPaymentData.customerMobile,\n customerEmail: fawryPaymentData.customerEmail,\n };\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComFawryPaymentStrategy from './checkoutcom-fawry-payment-strategy';\n\nconst createCheckoutComFawryPaymentStrategy: PaymentStrategyFactory<\n CheckoutComFawryPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComFawryPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComFawryPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'fawry' },\n]);\n","import { some } from 'lodash';\n\nimport { isRequestError, RequestError } from './';\n\nexport default function isThreeDSecureRequiredError(error: unknown): error is RequestError {\n return isRequestError(error) && some(error.body.errors, { code: 'three_d_secure_required' });\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isThreeDSecureRequiredError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CheckoutComCreditCardPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n protected formPoster: FormPoster,\n ) {\n super(paymentIntegrationService);\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (isThreeDSecureRequiredError(error)) {\n return this._handleThreeDSecure(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this.paymentIntegrationService.submitOrder(order, options);\n await form.submit(payment);\n } catch (error) {\n if (isThreeDSecureRequiredError(error)) {\n return this._handleThreeDSecure(error);\n }\n\n return Promise.reject(error);\n }\n\n this.paymentIntegrationService.loadCurrentOrder();\n }\n\n private _handleThreeDSecure(error: RequestError): Promise {\n const { acs_url, payer_auth_request, callback_url, merchant_data } =\n error.body.three_ds_result;\n\n return new Promise(() =>\n this.formPoster.postForm(acs_url, {\n PaReq: payer_auth_request || null,\n TermUrl: callback_url || null,\n MD: merchant_data || null,\n }),\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCreditCardPaymentStrategy from './checkoutcom-credit-card-payment-strategy';\n\nconst createCheckoutComCreditCardPaymentStrategy: PaymentStrategyFactory<\n CheckoutComCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComCreditCardPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createCheckoutComCreditCardPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'credit_card' },\n { gateway: 'checkoutcom', id: 'card' },\n]);\n","import {\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCheckoutcomSEPAInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_SEPA_PAYMENT_METHOD = 'sepa';\n\nexport default class CheckoutComSEPAPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomSEPAInstrument {\n const formattedPayload: WithCheckoutcomSEPAInstrument = { iban: '', bic: '' };\n const { iban, bic } =\n 'iban' in paymentData && 'bic' in paymentData ? paymentData : formattedPayload;\n\n if (methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD && document) {\n formattedPayload.iban = iban;\n formattedPayload.bic = bic;\n }\n\n return formattedPayload;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComSepaPaymentStrategy from './checkoutcom-sepa-payment-strategy';\n\nconst createCheckoutComSepaPaymentStrategy: PaymentStrategyFactory<\n CheckoutComSepaPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComSepaPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComSepaPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'sepa' },\n]);\n","import {\n CreditCardInstrument,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n WithIdealInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_IDEAL_PAYMENT_METHOD = 'ideal';\n\nexport default class CheckoutComiDealPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument | (CreditCardInstrument & WithIdealInstrument),\n ): WithIdealInstrument | undefined {\n if (CHECKOUTCOM_IDEAL_PAYMENT_METHOD === methodId && 'bic' in paymentData) {\n return { bic: paymentData.bic };\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComiDealPaymentStrategy from './checkoutcom-ideal-payment-strategy';\n\nconst createCheckoutComiDealPaymentStrategy: PaymentStrategyFactory<\n CheckoutComiDealPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComiDealPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComiDealPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'ideal' },\n]);\n","import {\n CreditCardInstrument,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithDocumentInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst DOCUMENT_SUPPORTED_APMS = ['boleto', 'oxxo', 'qpay', 'ideal'];\n\nexport default class CheckoutComAPMPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument | (CreditCardInstrument & WithDocumentInstrument),\n ): WithDocumentInstrument {\n const formattedPayload: WithDocumentInstrument = { ccDocument: '' };\n const ccDocument = 'ccDocument' in paymentData ? paymentData.ccDocument : '';\n\n if (DOCUMENT_SUPPORTED_APMS.indexOf(methodId) !== -1 && ccDocument) {\n formattedPayload.ccDocument = ccDocument;\n }\n\n return formattedPayload;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nimport CheckoutComAPMPaymentStrategy from './checkoutcom-apm-payment-strategy';\n\nconst createCheckoutComAPMPaymentStrategy: PaymentStrategyFactory<\n CheckoutComCustomPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComAPMPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComAPMPaymentStrategy, [\n { gateway: 'checkoutcom' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotCompletedError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpayScriptLoader from './clearpay-script-loader';\nimport ClearpaySdk from './clearpay-sdk';\n\nexport default class ClearpayPaymentStrategy implements PaymentStrategy {\n private _clearpaySdk?: ClearpaySdk;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _clearpayScriptLoader: ClearpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId, options.gatewayId);\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod);\n }\n\n deinitialize(): Promise {\n this._clearpaySdk = undefined;\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { gatewayId, methodId } = payload.payment || {};\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const state = this._paymentIntegrationService.getState();\n const { isStoreCreditApplied: useStoreCredit } = state.getCheckoutOrThrow();\n\n await this._paymentIntegrationService.applyStoreCredit(useStoreCredit);\n\n await this._paymentIntegrationService.validateCheckout(state.getCheckout(), options);\n\n const { countryCode } = state.getBillingAddressOrThrow();\n\n if (!this._isCountrySupported(countryCode)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because billing country is not supported.',\n );\n }\n\n await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToClearpay(\n countryCode,\n this._paymentIntegrationService.getState().getPaymentMethod(methodId, gatewayId),\n );\n\n // Clearpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(noop);\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n const config = state.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._paymentIntegrationService.submitOrder({}, options);\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._paymentIntegrationService.forgetCheckout(payment.providerId);\n await this._paymentIntegrationService.loadPaymentMethods();\n\n if (isRequestError(error)) {\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n }\n\n private async _redirectToClearpay(\n countryCode: string,\n paymentMethod?: PaymentMethod,\n ): Promise {\n if (!this._clearpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._clearpaySdk.initialize({ countryCode });\n this._clearpaySdk.redirect({ token: paymentMethod.clientToken });\n\n return Promise.resolve();\n }\n\n private _isCountrySupported(countryCode: string): boolean {\n return countryCode === 'GB';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n });\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Clearpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpaySdk from './clearpay-sdk';\nimport ClearpayWindow from './clearpay-window';\n\nconst SCRIPTS_DEFAULT = {\n PROD: '//portal.clearpay.co.uk/afterpay-async.js',\n SANDBOX: '//portal.sandbox.clearpay.co.uk/afterpay-async.js',\n};\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean): string {\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpayPaymentStrategy from './clearpay-payment-strategy';\nimport ClearpayScriptLoader from './clearpay-script-loader';\n\nconst createClearpayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new ClearpayPaymentStrategy(\n paymentIntegrationService,\n new ClearpayScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createClearpayPaymentStrategy, [\n { gateway: 'clearpay' },\n { id: 'clearpay' },\n]);\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CreditCardPaymentStrategy from './credit-card-payment-strategy';\n\nconst createCreditCardPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CreditCardPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCreditCardPaymentStrategy, [{ default: true }]);\n","import { merge, some } from 'lodash';\n\nimport {\n HostedForm,\n isRequestError,\n isVaultedInstrument,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlow {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n await this._cardinalClient.configure(await this._getClientToken(method));\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const { getCardInstrument, getPaymentMethodOrThrow } =\n this._paymentIntegrationService.getState();\n\n const { payment: { methodId = '', paymentData = {} } = {} } = payload;\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const bin = instrument ? instrument.iin : hostedForm && hostedForm.getBin();\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await execute(\n merge(payload, {\n payment: {\n paymentData: {\n threeDSecure: { token: getPaymentMethodOrThrow(methodId).clientToken },\n },\n },\n }),\n options,\n );\n } catch (error) {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n const threeDSecure = await this._cardinalClient.getThreeDSecureData(\n error.body.three_ds_result,\n this._getOrderData(),\n );\n\n if (!hostedForm) {\n await this._paymentIntegrationService.submitPayment(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n\n return;\n }\n\n await hostedForm.submit(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n }\n }\n\n private async _getClientToken(method: PaymentMethod): Promise {\n if (method.clientToken) {\n return method.clientToken;\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(method.id);\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(method.id);\n\n return paymentMethod.clientToken || '';\n }\n\n private _getOrderData(): CardinalOrderData {\n const state = this._paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const shippingAddress = state.getShippingAddress();\n const checkout = state.getCheckoutOrThrow();\n const order = state.getOrderOrThrow();\n\n return {\n billingAddress,\n shippingAddress,\n currencyCode: checkout.cart.currency.code,\n id: order.orderId.toString(),\n amount: checkout.cart.cartAmount,\n };\n }\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport type setupCompleteFn = (setupCompleteData: CardinalSetupCompletedData) => void;\nexport type validatedFn = (data: CardinalValidatedData, jwt?: string) => void;\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted]: setupCompleteFn;\n [CardinalEventType.Validated]: validatedFn;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes, noop } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n CreditCardInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethodFailedError,\n ThreeDSecureToken,\n ThreeDsResult,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(noop);\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(noop),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { CardinalThreeDSecureFlow } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CyberSourcePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(_paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CyberSourcePaymentStrategy from './cybersource-payment-strategy';\n\nconst createCyberSourcePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CyberSourcePaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlow(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n};\n\nexport default toResolvableModule(createCyberSourcePaymentStrategy, [{ id: 'cybersource' }]);\n","import { merge, some } from 'lodash';\n\nimport {\n HostedForm,\n isCreditCardInstrument,\n isRequestError,\n isVaultedInstrument,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const { getCardInstrument } = this._paymentIntegrationService.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (isRequestError(error) && error.body?.status === 'additional_action_required') {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (err) {\n if (\n isRequestError(err) &&\n some(err.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = err.body.three_ds_result;\n const threeDsToken = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return this._submitPayment(payment, { token: threeDsToken }, hostedForm);\n }\n\n throw err;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._paymentIntegrationService.getState();\n const billingAddress = store.getBillingAddressOrThrow();\n const shippingAddress = store.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.getCheckoutOrThrow();\n const id = store.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n await hostedForm?.submit(paymentPayload);\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: PaymentIntegrationSelectors['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardInstrument(paymentData) && paymentData.ccNumber;\n const hostedFormBin = hostedForm ? hostedForm.getBin() : ccNumber;\n const bin = instrument ? instrument.iin : hostedFormBin;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument } from './payment';\n\nexport default function isCreditCardInstrument(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { CardinalThreeDSecureFlowV2 } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CyberSourceV2PaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(_paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlowV2,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CyberSourceV2PaymentStrategy from './cybersourcev2-payment-strategy';\n\nconst createCyberSourceV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CyberSourceV2PaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlowV2(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n};\n\nexport default toResolvableModule(createCyberSourceV2PaymentStrategy, [{ id: 'cybersourcev2' }]);\n","export interface DigitalRiverWindow extends Window {\n /**\n * Object to create an instance of the DigitalRiver object. This is called a Digital River publishable API key\n * This function accepts an optional options object using the following format DigitalRiver(publishableApiKey{, options})\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n DigitalRiver?: DigitalRiverClass;\n}\n\nexport type DigitalRiverClass = new (\n apiKey: string,\n options?: DigitalRiverJSOptions,\n) => DigitalRiverJS;\n\nexport default interface DigitalRiverJS {\n createDropin(configuration: DigitalRiverDropInConfiguration): DigitalRiverDropIn;\n authenticateSource(\n data: DigitalRiverAuthenticateSourceRequest,\n ): Promise;\n createElement(type: string, options: DigitalRiverElementOptions): DigitalRiverElement;\n}\n\nexport interface DigitalRiverElementOptions {\n classes: {\n base: string;\n };\n compliance: {\n entity: string;\n };\n}\n\ninterface DigitalRiverAuthenticateSourceRequest {\n sessionId: string;\n sourceId: string;\n sourceClientSecret: string;\n}\n\nexport interface DigitalRiverAdditionalProviderData {\n source_id: string;\n source_client_secret: string;\n}\n\nexport interface DigitalRiverAuthenticateSourceResponse {\n status: AuthenticationSourceStatus;\n}\n\nexport enum AuthenticationSourceStatus {\n complete = 'complete',\n authentication_not_required = 'authentication_not_required',\n failed = 'failed',\n}\n\nexport interface DigitalRiverJSOptions {\n /**\n * The locale used to localize the various display and error strings within DigitalRiver.js\n * Currently supported locales:\n * ar-EG, cs-CZ, da-DK, de-AT, de-CH, de-DE, el-GR, en-AU, en-BE, en-CA, en-CH, en-DK, en-FI, en-GB, en-IE, en-IN,\n * en-MY, en-NL, en-NO, en-NZ, en-PR, en-SE, en-SG, en-US, en-ZA, es-AR, es-CL, es-CO, es-EC, es-ES, es-MX, es-PE,\n * es-VE, et-EE, fi-FI, fr-BE, fr-CA, fr-CH, fr-FR, hu-HU, it-CH, it-IT, iw-IL, ja-JP, ko-KR, lt-LT, lv-LV, nl-BE,\n * nl-NL, no-NO, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-YU, sv-SE, th-TH, tr-TR, zh-CN, zh-HK, zh-TW\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n locale?: string;\n}\n\n/**\n * Create a Configuration object for Drop-in\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-5-configure-hydrate\n */\nexport interface DigitalRiverDropInConfiguration {\n /**\n * The payment session identifier returned by Digital River.\n */\n sessionId: string;\n\n /**\n * you can specify options to trigger different features or functionality\n */\n options?: OptionsResponse;\n billingAddress: {\n firstName: string;\n lastName: string;\n email: string;\n phoneNumber: string;\n address: {\n line1: string;\n line2?: string;\n city?: string;\n state?: string;\n postalCode: string;\n country: string;\n };\n };\n\n /**\n * Additional configuration details for configuration structure (classes, styles etc..)\n */\n paymentMethodConfiguration?: BaseElementOptions;\n\n /**\n * The function called when the shopper has authorized payment and a payment source has been successfully created.\n */\n onSuccess?(data: OnSuccessResponse): void;\n\n /**\n * The function called when the shopper cancels the payment process before authorizing payment.\n */\n onCancel?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when an error has occurred.\n */\n onError?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when Drop-in is ready for user interaction.\n */\n onReady?(data: OnReadyResponse): void;\n}\n\nexport interface OnCancelOrErrorResponse {\n /**\n * If an error occurs, Drop-in emits an event that identifies the payment method associated with the error.\n * Instruct your customer to provide a new method of payment.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onerror\n * Or When your customer chooses to pay with a specific payment method and decides to cancel during the redirect phase,\n * Drop-in emits an event that identifies the cancelled payment method.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#oncancel\n */\n errors: ErrorData[];\n}\n\nexport interface ErrorData {\n code: string;\n message: string;\n}\n\nexport interface OnReadyResponse {\n /**\n * When ready, Drop-in will emit an event that contains a \"paymentMethodTypes\" array of the available payment methods.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onready\n */\n paymentMethodTypes: string[];\n}\n\n/**\n * When creating your Drop-in instance, you can specify options to trigger different features or functionality.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options\n */\nexport interface OptionsResponse {\n /**\n * Use this option if you are using Drop-in within a standard checkout flow. Example Value: \"checkout\"\n */\n flow?: string;\n\n /**\n * When enabled, presents the customer with an option to save their payment details for future use within Drop-in.\n * Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate\n * any necessary Strong Customer Authentication.\n * If disabled, Drop-in will not present the customer with an option to save their payment details.\n */\n showSavePaymentAgreement?: boolean;\n\n /**\n * Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.\n */\n showComplianceSection?: boolean;\n\n /**\n * Use this option to customize the text of the Drop-in button.\n */\n button?: ButtonResponse;\n\n /**\n * Use this option to specify the future use of a source.\n */\n usage?: string;\n\n /**\n * Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.\n */\n showTermsOfSaleDisclosure?: boolean;\n\n /**\n * Additional configuration details for drop-in.\n */\n paymentMethodConfiguration?: BaseElementOptions;\n}\n\nexport interface ButtonResponse {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#customizing-the-text-of-the-drop-in-button\n * The text of the Drop-in button is customizable. You can either display pre-configured text or you can specify a unique text\n * Examples type: \"payNow\" || type: \"buyNow\" || type: \"completeOrder\" || type: \"submitOrder\"\n */\n type: string;\n}\n\nexport interface OnSuccessResponse {\n /**\n * Event that gets triggered after the customer's payment has provided with the necessary details for payment\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onsuccess\n */\n source: {\n id: string;\n reusable: boolean;\n browserInfo?: {\n browserIp?: string;\n };\n owner?: {\n email: string;\n firstName: string;\n lastName: string;\n phoneNumber: string;\n address: {\n city: string;\n country: string;\n line1: string;\n postalCode: string;\n state: string;\n };\n };\n };\n\n /**\n * Indicates whether the source has been enabled for future use.\n * Important: If this value is true, it does not mean the customer can use this source multiple times.\n * This flag identifies whether the necessary downstream actions have been triggered to prepare the source for storage.\n * You must attach the source to your customer for it to be truly reusable.\n */\n readyForStorage: boolean;\n}\n\nexport interface DigitalRiverDropIn {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface DigitalRiverElement {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface BaseElementOptions {\n /**\n * Set custom class names on the container DOM element when the Digital River element is in a particular state.\n */\n classes?: DigitalRiverElementClasses;\n /**\n * Use disabledPaymentMethods to disable specific payment methods.\n */\n disabledPaymentMethods?: string[];\n}\n\n/**\n * Custom classes\n * You can specify custom classes as part of a Class object included within the Options object when you create or\n * update an element. If you do not provide custom classes, the system uses the default options.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/elements#custom-classes\n */\nexport interface DigitalRiverElementClasses {\n /**\n * The Element is in its base state. The user either has not entered anything into the input field or is currently typing.\n */\n base?: string;\n\n /**\n * The Element is in its complete state. The user has input value, and it meets the basic validation requirements of that field.\n */\n complete?: string;\n\n /**\n * The Element is empty. The Element once had value but is now empty.\n */\n empty?: string;\n\n /**\n * The Element has focus.\n */\n focus?: string;\n\n /**\n * The Element has value, but it does not meet the basic validation requirements of the field.\n */\n invalid?: string;\n\n /**\n * The element has a value that has been automatically filled by the browser.\n */\n webkitAutofill?: string;\n}\n\nexport interface DigitalRiverInitializeToken {\n sessionId: string;\n checkoutData: DigitalRiverCheckoutData;\n}\n\ninterface DigitalRiverCheckoutData {\n checkoutId: string;\n sellingEntity: string;\n}\n\nexport interface DigitalRiverInitializationData {\n publicKey: string;\n paymentLanguage: string;\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nconst defaultMessage =\n 'There was an error while processing your payment. Please try again or contact us.';\n\nexport default class DigitalRiverError extends StandardError {\n constructor(type: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.type = type;\n this.name = name;\n }\n}\n","import { some } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverJS, {\n AuthenticationSourceStatus,\n DigitalRiverAdditionalProviderData,\n DigitalRiverAuthenticateSourceResponse,\n DigitalRiverDropIn,\n DigitalRiverElementOptions,\n DigitalRiverInitializationData,\n DigitalRiverInitializeToken,\n OnCancelOrErrorResponse,\n OnReadyResponse,\n OnSuccessResponse,\n} from './digitalriver';\nimport DigitalRiverError from './digitalriver-error';\nimport DigitalRiverPaymentInitializeOptions, {\n WithDigitalRiverPaymentInitializeOptions,\n} from './digitalriver-payment-initialize-options';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nexport default class DigitalRiverPaymentStrategy implements PaymentStrategy {\n private digitalRiverJS?: DigitalRiverJS;\n private digitalRiverDropComponent?: DigitalRiverDropIn;\n private submitFormEvent?: () => void;\n private loadSuccessResponse?: OnSuccessResponse;\n private digitalRiverCheckoutData?: DigitalRiverInitializeToken;\n private unsubscribe?: () => void;\n private digitalRiverInitializeOptions?: DigitalRiverPaymentInitializeOptions;\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private digitalRiverScriptLoader: DigitalRiverScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithDigitalRiverPaymentInitializeOptions,\n ): Promise {\n this.digitalRiverInitializeOptions = options.digitalriver;\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { publicKey, paymentLanguage: locale } = paymentMethod.initializationData || {};\n const { containerId } = this.getDigitalRiverInitializeOptions();\n\n if (!publicKey || !locale) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publicKey\" or \"locale\" argument is not provided.',\n );\n }\n\n this.digitalRiverJS = await this.digitalRiverScriptLoader.load(publicKey, locale);\n\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n async (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n\n this.digitalRiverJS = await this.digitalRiverScriptLoader.load(\n publicKey,\n locale,\n );\n }\n\n await this.loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n this.loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n const { containerId } = this.getDigitalRiverInitializeOptions();\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n }\n\n return Promise.resolve();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, methodId } = payment;\n const { shouldSetAsDefaultInstrument = false } = isHostedInstrumentLike(paymentData)\n ? paymentData\n : {};\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (!this.digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (isVaultedInstrument(paymentData)) {\n try {\n await this.submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this.digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n false,\n );\n } catch (error) {\n if (!this.isAuthenticateSourceAction(error)) {\n throw error;\n }\n\n const confirm =\n isRequestError(error) &&\n (await this.authenticateSource(error.body.provider_data));\n\n await this.submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this.digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n confirm,\n );\n }\n } else {\n if (!this.loadSuccessResponse) {\n throw new PaymentArgumentInvalidError(['this.loadSuccessResponse']);\n }\n\n const paymentPayload = {\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n checkoutId: this.digitalRiverCheckoutData.checkoutData.checkoutId,\n source: this.loadSuccessResponse,\n sessionId: this.digitalRiverCheckoutData.sessionId,\n }),\n },\n vault_payment_instrument: this.loadSuccessResponse.readyForStorage,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private getDigitalRiverJs(): DigitalRiverJS {\n if (!this.digitalRiverJS) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.digitalRiverJS;\n }\n\n private getErrorMessage(error: OnCancelOrErrorResponse): string {\n const { errors } = error;\n\n return errors.map((e) => `code: ${e.code} message: ${e.message}`).join('\\n');\n }\n\n private async onSuccessResponse(data?: OnSuccessResponse): Promise {\n const error = new InvalidArgumentError(\n 'Unable to initialize payment because success argument is not provided.',\n );\n\n if (data && this.submitFormEvent) {\n const { browserInfo, owner } = data.source;\n\n this.loadSuccessResponse = browserInfo\n ? {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n ...browserInfo,\n },\n readyForStorage: data.readyForStorage,\n }\n : {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n },\n readyForStorage: data.readyForStorage,\n };\n\n if (owner) {\n const billingAddressPayPal = {\n firstName: owner.firstName,\n lastName: owner.lastName,\n city: owner.address.city,\n company: '',\n address1: owner.address.line1,\n address2: '',\n postalCode: owner.address.postalCode,\n countryCode: owner.address.country,\n phone: owner.phoneNumber,\n stateOrProvince: owner.address.state,\n stateOrProvinceCode: owner.address.country,\n customFields: [],\n email: owner.email || owner.email,\n };\n\n this.loadSuccessResponse.source.owner = data.source.owner;\n await this.paymentIntegrationService.updateBillingAddress(billingAddressPayPal);\n }\n\n return this.submitFormEvent();\n }\n\n return this.getDigitalRiverInitializeOptions().onError?.(error);\n }\n\n private onReadyResponse(data?: OnReadyResponse): void {\n if (data) {\n this.getDigitalRiverInitializeOptions().onRenderButton?.();\n }\n }\n\n private getDigitalRiverInitializeOptions(): DigitalRiverPaymentInitializeOptions {\n if (!this.digitalRiverInitializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.digitalRiverInitializeOptions;\n }\n\n private async loadWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n try {\n const state = await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n const billing = state.getBillingAddressOrThrow();\n const customer = state.getCustomerOrThrow();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const { paymentMethodConfiguration } =\n this.getDigitalRiverInitializeOptions().configuration;\n const { containerId, configuration } = this.getDigitalRiverInitializeOptions();\n const { clientToken } = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.digitalRiverCheckoutData = JSON.parse(clientToken);\n\n if (!this.digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.mountComplianceSection(this.digitalRiverCheckoutData.checkoutData.sellingEntity);\n\n this.submitFormEvent = this.getDigitalRiverInitializeOptions().onSubmitForm;\n\n const disabledPaymentMethods = features['PROJECT-4802.digital_river_paypal_support']\n ? []\n : ['payPal'];\n\n const digitalRiverConfiguration = {\n sessionId: this.digitalRiverCheckoutData.sessionId,\n options: {\n ...configuration,\n showSavePaymentAgreement:\n Boolean(customer.email) && configuration.showSavePaymentAgreement,\n },\n billingAddress: {\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email || customer.email,\n phoneNumber: billing.phone,\n address: {\n line1: billing.address1,\n line2: billing.address2,\n city: billing.city,\n state: billing.stateOrProvinceCode,\n postalCode: billing.postalCode,\n country: billing.countryCode,\n },\n },\n paymentMethodConfiguration: {\n ...paymentMethodConfiguration,\n disabledPaymentMethods,\n },\n onSuccess: (data?: OnSuccessResponse) => {\n this.onSuccessResponse(data);\n },\n onReady: (data?: OnReadyResponse) => {\n this.onReadyResponse(data);\n },\n onError: (error: OnCancelOrErrorResponse) => {\n const descriptiveError = new Error(this.getErrorMessage(error));\n\n this.getDigitalRiverInitializeOptions().onError?.(descriptiveError);\n },\n };\n\n this.digitalRiverDropComponent =\n this.getDigitalRiverJs().createDropin(digitalRiverConfiguration);\n this.digitalRiverDropComponent.mount(containerId);\n\n return state;\n } catch {\n throw new DigitalRiverError(\n 'payment.digitalriver_checkout_error',\n 'digitalRiverCheckoutError',\n );\n }\n }\n\n private isAuthenticateSourceAction(error: unknown): boolean {\n return !(\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n );\n }\n\n private async authenticateSource(\n additionalAction: DigitalRiverAdditionalProviderData,\n ): Promise {\n if (!this.digitalRiverCheckoutData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because payload payment argument is not provided.',\n );\n }\n\n const authenticateSourceResponse: DigitalRiverAuthenticateSourceResponse =\n await this.getDigitalRiverJs().authenticateSource({\n sessionId: this.digitalRiverCheckoutData.sessionId,\n sourceId: additionalAction.source_id,\n sourceClientSecret: additionalAction.source_client_secret,\n });\n\n if (authenticateSourceResponse.status === AuthenticationSourceStatus.failed) {\n throw new Error('Source authentication failed, please try again');\n }\n\n return (\n authenticateSourceResponse.status === AuthenticationSourceStatus.complete ||\n authenticateSourceResponse.status ===\n AuthenticationSourceStatus.authentication_not_required\n );\n }\n\n private async submitVaultedInstrument(\n methodId: string,\n instrumentId: string,\n checkoutId: string,\n shouldSetAsDefaultInstrument: boolean,\n confirm: boolean,\n ): Promise {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n token: instrumentId,\n },\n credit_card_token: {\n token: JSON.stringify({\n checkoutId,\n }),\n },\n confirm,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n };\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private mountComplianceSection(sellingEntity: string) {\n const complianceDiv = document.getElementById('compliance');\n\n const complianceOptions: DigitalRiverElementOptions = {\n classes: {\n base: 'DRElement',\n },\n compliance: {\n entity: sellingEntity,\n },\n };\n\n if (complianceDiv) {\n complianceDiv.innerHTML = '';\n\n const complianceElement = this.getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n } else {\n const drfooter = document.createElement('div');\n\n drfooter.setAttribute('id', 'compliance');\n drfooter.style.cssText = 'min-height: 45px;';\n drfooter.classList.add('layout');\n document.body.appendChild(drfooter);\n\n const complianceElement = this.getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n }\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverJS, { DigitalRiverWindow } from './digitalriver';\n\nexport default class DigitalRiverScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stylesheetLoader: StylesheetLoader,\n private _window: DigitalRiverWindow = window,\n ) {}\n\n async load(publicKey: string, locale: string): Promise {\n await Promise.all([\n this.stylesheetLoader.loadStylesheet(\n `https://js.digitalriverws.com/v1/css/DigitalRiver.css`,\n ),\n this.scriptLoader.loadScript(`https://js.digitalriverws.com/v1/DigitalRiver.js`),\n ]);\n\n if (!this._window.DigitalRiver) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(new this._window.DigitalRiver(publicKey, { locale }));\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverPaymentStrategy from './digitalriver-payment-strategy';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nconst createDigitalRiverPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new DigitalRiverPaymentStrategy(\n paymentIntegrationService,\n new DigitalRiverScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n\nexport default toResolvableModule(createDigitalRiverPaymentStrategy, [{ id: 'digitalriver' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n isRequestError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, isAdditionalActionRequired } from './is-additional-action';\n\nexport default class ExternalPaymentStrategy implements PaymentStrategy {\n constructor(\n private _formPoster: FormPoster,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (\n !isRequestError(error) ||\n !isAdditionalActionRequired(error.body) ||\n !this._isAdditionalActionRequired(error.body)\n ) {\n return Promise.reject(error);\n }\n\n const {\n body: {\n additional_action_required: {\n data: { redirect_url },\n },\n },\n } = error;\n\n return new Promise(() => this.redirectUrl(redirect_url));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n protected redirectUrl(redirect_url: string): void {\n return this._formPoster.postForm(redirect_url, {});\n }\n\n private _isAdditionalActionRequired(body: AdditionalActionRequired): boolean {\n const { additional_action_required, status } = body;\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'offsite_redirect'\n );\n }\n}\n","export interface AdditionalActionRequired {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n type: string;\n };\n status: string;\n}\n\nexport function isAdditionalActionRequired(value: unknown): value is AdditionalActionRequired {\n return typeof value === 'object' && value !== null && 'additional_action_required' in value;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ExternalPaymentStrategy from './external-payment-strategy';\n\nconst createExternalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new ExternalPaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createExternalPaymentStrategy, [{ id: 'laybuy' }]);\n","import { AdyenAdditionalActionErrorResponse } from '../types';\n\nexport default function isAdditionalActionRequiredErrorResponse(\n param: unknown,\n): param is AdyenAdditionalActionErrorResponse {\n return (\n typeof param === 'object' &&\n param !== null &&\n 'errors' in (param as AdyenAdditionalActionErrorResponse) &&\n Array.isArray((param as AdyenAdditionalActionErrorResponse).errors) &&\n 'code' in (param as AdyenAdditionalActionErrorResponse).errors[0] &&\n typeof (param as AdyenAdditionalActionErrorResponse).errors[0].code === 'string' &&\n 'provider_data' in param &&\n typeof (param as AdyenAdditionalActionErrorResponse).provider_data === 'object'\n );\n}\n","import {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV2ScriptLoader,\n isAdditionalActionRequiredErrorResponse,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAdyenV2 extends GooglePayGateway {\n private _adyenClient?: AdyenClient;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _scriptLoader: AdyenV2ScriptLoader) {\n super('adyen', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n const state = this._service.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n });\n\n return Promise.resolve();\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n const paymentMethod = super.getPaymentMethod();\n\n return JSON.stringify({\n type: paymentMethod.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isRequestError(error) || !isAdditionalActionRequiredErrorResponse(error.body)) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._service.submitPayment(payment);\n } catch (e) {\n return this.processAdditionalAction(e);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { round } from 'lodash';\n\nimport {\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayPaymentInitializeOptions, {\n WithGooglePayPaymentInitializeOptions,\n} from './google-pay-payment-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n CallbackTriggerType,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithGooglePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n const googlePayOptions = options[this._getMethodId()];\n\n if (!googlePayOptions?.walletButton) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n const { walletButton, ...callbacks } = googlePayOptions;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(paymentMethod.initializationData?.storeCountry),\n );\n\n this._addPaymentButton(walletButton, callbacks);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n const nonce = await this._googlePayPaymentProcessor.getNonce(payment.methodId);\n const extraData = await this._googlePayPaymentProcessor.extraPaymentData();\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce, ...extraData },\n });\n } catch (error) {\n await this._googlePayPaymentProcessor.processAdditionalAction(error, payment.methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._clickListener) {\n this._paymentButton?.removeEventListener('click', this._clickListener);\n }\n\n this._paymentButton = undefined;\n this._clickListener = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n protected _addPaymentButton(\n walletButton: string,\n callbacks: Omit,\n ): void {\n if (this._paymentButton) {\n return;\n }\n\n const paymentButton = document.getElementById(walletButton);\n\n if (!paymentButton) {\n throw new InvalidArgumentError('Unable to proceed without a walletButton.');\n }\n\n this._paymentButton = paymentButton;\n this._clickListener = this._handleClick(callbacks);\n\n this._paymentButton.addEventListener('click', this._clickListener);\n }\n\n protected _handleClick({\n onPaymentSelect,\n onError,\n }: Omit): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n // TODO: Dispatch Widget Actions\n try {\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(), response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n }: IntermediatePaymentData): Promise => {\n if (callbackTrigger !== CallbackTriggerType.INITIALIZE) {\n return;\n }\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCartOrThrow } =\n this._paymentIntegrationService.getState();\n const { code: currencyCode, decimalPlaces } = getCartOrThrow().currency;\n const totalPrice = round(\n getCheckoutOrThrow().outstandingBalance,\n decimalPlaces,\n ).toFixed(decimalPlaces);\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n };\n },\n },\n };\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV2ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAdyenV2Gateway from '../../gateways/google-pay-adyenv2-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAdyenV2Gateway(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAdyenV2PaymentStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV3ScriptLoader,\n isAdditionalActionRequiredErrorResponse,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAdyenV3 extends GooglePayGateway {\n private _adyenClient?: AdyenClient;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _scriptLoader: AdyenV3ScriptLoader) {\n super('adyen', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n const state = this._service.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n });\n\n return Promise.resolve();\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isRequestError(error) || !isAdditionalActionRequiredErrorResponse(error.body)) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._service.submitPayment(payment);\n } catch (e) {\n return this.processAdditionalAction(e);\n }\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n const paymentMethod = super.getPaymentMethod();\n\n return JSON.stringify({\n type: paymentMethod.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV3ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAdyenV3Gateway from '../../gateways/google-pay-adyenv3-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAdyenV3Gateway(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAdyenV3PaymentStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeNetPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAuthorizeNetPaymentStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComPaymentStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourcePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayCybersourcePaymentStrategy, [\n { id: 'googlepaycybersourcev2' },\n { id: 'googlepaybnz' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayOrbitalPaymentStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayWorldpayAccessPaymentStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreePaymentStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","export type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\nexport interface PayPalSDK {\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n };\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n}\n\ninterface PayerActionConfig {\n orderId: string;\n}\n\nexport enum ConfirmOrderStatus {\n Approved = 'APPROVED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n}\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface PayPalCommerceScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n | 'buttons'\n | 'funding-eligibility'\n | 'hosted-fields'\n | 'messages'\n | 'payment-fields'\n | 'legal'\n | 'googlepay'\n | 'card-fields'\n>;\n\nexport interface GooglePayConfig {\n allowedPaymentMethods: AllowedPaymentMethods[];\n apiVersion: number;\n apiVersionMinor: number;\n countryCode: string;\n isEligible: boolean;\n merchantInfo: {\n merchantId: string;\n merchantOrigin: string;\n };\n}\n\nexport interface AllowedPaymentMethods {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n billingAddressRequired: boolean;\n assuranceDetailsRequired: boolean;\n billingAddressParameters: {\n format: string;\n };\n };\n tokenizationSpecification: {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId: string;\n };\n };\n}\n\nexport interface PayPalGoogleSdk {\n version: string;\n getCorrelationID: () => void;\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (arg0: {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n }) => Promise<{ status: string }>;\n initiatePayerAction: () => void;\n };\n FUNDING: Record;\n}\n\nexport interface ConfirmOrderData {\n tokenizationData: {\n type: string;\n token: string;\n };\n info: {\n cardNetwork: string;\n cardDetails: string;\n };\n type: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n private _requestSender: RequestSender,\n ) {\n super(_paymentIntegrationService, _googlePayPaymentProcessor);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const state = this._paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const { initializationData } = state.getPaymentMethodOrThrow(\n this._getMethodId(),\n );\n const { orderId } = await this.getOrderId(cartId);\n\n const { card_information } = initializationData || {};\n const nonce = await this._googlePayPaymentProcessor.getNonce(payment.methodId);\n\n const confirmOrderData = {\n tokenizationData: {\n type: 'PAYMENT_GATEWAY',\n token: atob(nonce),\n },\n info: {\n cardNetwork: card_information?.type || '',\n cardDetails: card_information?.number || '',\n },\n type: 'CARD',\n };\n\n await this.confirmOrder(orderId, confirmOrderData);\n await this._paymentIntegrationService.submitOrder();\n\n try {\n const paymentData = {\n formattedPayload: {\n method_id: payment.methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n } catch (error) {\n await this._googlePayPaymentProcessor.processAdditionalAction(error);\n }\n }\n\n private async confirmOrder(orderId: string, confirmOrderData: ConfirmOrderData) {\n const state = this._paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(\n this._getMethodId(),\n );\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n true,\n );\n\n const { status } = await payPalSDK\n .Googlepay()\n .confirmOrder({ orderId, paymentMethodData: confirmOrderData });\n\n if (status === ConfirmOrderStatus.PayerActionRequired) {\n await payPalSDK.Googlepay().initiatePayerAction({ orderId });\n\n return Promise.resolve();\n }\n\n if (status !== ConfirmOrderStatus.Approved) {\n throw new InvalidArgumentError('Payment is not approved.');\n }\n\n return Promise.resolve();\n }\n\n private async getOrderId(cartId: string): Promise<{ orderId: string }> {\n const url = '/api/storefront/payments/googlepaypaypalcommercecheckout';\n const requestData = {\n cartId,\n shouldSaveInstrument: false,\n };\n\n const { body } = await this._requestSender.post<{ orderId: string }>(url, {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n },\n body: requestData,\n });\n\n return body;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport GooglePayPaypalCommercePaymentStrategy from './google-pay-paypal-commerce-payment-strategy';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const scriptLoader = new PayPalCommerceScriptLoader(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, scriptLoader),\n createRequestSender(),\n createFormPoster(),\n ),\n scriptLoader,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartPaymentStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import StandardError from './standard-error';\n\nconst defaultMessage =\n 'Payment cannot be processed for this order, please select another payment method';\n\nexport default class PaymentExecuteError extends StandardError {\n type = 'custom_provider_execute_error';\n subtype: string;\n\n constructor(subtype: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.name = name;\n this.subtype = subtype;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentExecuteError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { HummInitializationData, OffsiteRedirectResponse } from './humm';\n\nexport default class HummPaymentStrategy implements PaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(payment.methodId, options);\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payment.methodId);\n\n if (!paymentMethod.initializationData?.processable) {\n throw new PaymentExecuteError(\n 'payment.humm_not_processable_error',\n 'hummNotProcessableError',\n );\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n });\n } catch (error) {\n if (this.isOffsiteRedirectResponse(error)) {\n return this.handleOffsiteRedirectResponse(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private handleOffsiteRedirectResponse(response: OffsiteRedirectResponse): Promise {\n const url = response.body.additional_action_required.data.redirect_url;\n const data = response.body.provider_data;\n\n return new Promise((resolve) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.formPoster.postForm(url, JSON.parse(data), resolve);\n });\n }\n\n private isOffsiteRedirectResponse(response: unknown): response is OffsiteRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n partialBody.additional_action_required.type === 'offsite_redirect' &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HummPaymentStrategy from './humm-payment-strategy';\n\nconst createHummPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new HummPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createHummPaymentStrategy, [{ id: 'humm' }]);\n","export const supportedCountries = [\n 'AT',\n 'BE',\n 'CA',\n 'CH',\n 'CZ',\n 'DE',\n 'DK',\n 'ES',\n 'FI',\n 'FR',\n 'GB',\n 'GR',\n 'IE',\n 'IT',\n 'NL',\n 'NO',\n 'NZ',\n 'PL',\n 'PT',\n 'SE',\n];\nexport const supportedCountriesRequiringStates = ['AU'];\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { includes } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from '../klarnav2/klarna-supported-countries';\n\nimport KlarnaCredit, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-credit';\nimport { WithKlarnaPaymentInitializeOptions } from './klarna-payment-initialize-options';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nexport default class KlarnaPaymentStrategy {\n private klarnaCredit?: KlarnaCredit;\n private unsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private klarnaScriptLoader: KlarnaScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithKlarnaPaymentInitializeOptions,\n ): Promise {\n this.klarnaCredit = await this.klarnaScriptLoader.load();\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n void this.loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n await this.loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n\n const { authorization_token: authorizationToken } = await this.authorize();\n\n await this.paymentIntegrationService.initializePayment(paymentPayload.methodId, {\n authorizationToken,\n });\n\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async loadWidget(\n options: PaymentInitializeOptions & WithKlarnaPaymentInitializeOptions,\n ): Promise {\n if (!options.klarna) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarna\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n klarna: { container, onLoad },\n } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n return new Promise((resolve) => {\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!this.klarnaCredit || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.klarnaCredit.init({ client_token: paymentMethod.clientToken });\n\n this.klarnaCredit.load({ container }, (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n });\n });\n }\n\n private getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this.mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this.needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private authorize(): Promise {\n return new Promise((resolve, reject) => {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddress();\n const shippingAddress = state.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n if (!this.klarnaCredit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const updateSessionData = this.getUpdateSessionData(billingAddress, shippingAddress);\n\n this.klarnaCredit.authorize(updateSessionData, (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaCredit from './klarna-credit';\nimport KlarnaWindow from './klarna-window';\n\nconst SDK_URL = '//credit.klarnacdn.net/lib/v1/api.js';\n\nexport default class KlarnaScriptLoader {\n constructor(private scriptLoader: ScriptLoader, private klarnaWindow: KlarnaWindow = window) {}\n\n async load(): Promise {\n if (!this.klarnaWindow.Klarna?.Credit) {\n await this.scriptLoader.loadScript(SDK_URL);\n }\n\n if (!this.klarnaWindow.Klarna?.Credit) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.klarnaWindow.Klarna.Credit;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPaymentStrategy from './klarna-payment-strategy';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nconst createKlarnaPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new KlarnaPaymentStrategy(\n paymentIntegrationService,\n new KlarnaScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createKlarnaPaymentStrategy, [{ id: 'klarna' }]);\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { includes } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-payments';\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from './klarna-supported-countries';\nimport { WithKlarnaV2PaymentInitializeOptions } from './klarnav2-payment-initialize-options';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nexport default class KlarnaV2PaymentStrategy {\n private klarnaPayments?: KlarnaPayments;\n private unsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private klarnav2ScriptLoader: KlarnaV2ScriptLoader,\n private klarnav2TokenUpdater: KlarnaV2TokenUpdater,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithKlarnaV2PaymentInitializeOptions,\n ): Promise {\n this.klarnaPayments = await this.klarnav2ScriptLoader.load();\n\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n void this.loadPaymentsWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n await this.loadPaymentsWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { ...paymentPayload },\n } = payload;\n const { gatewayId, methodId } = paymentPayload;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { id: cartId } = state.getCartOrThrow();\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(methodId);\n\n await this.paymentIntegrationService.initializePayment(gatewayId, {\n authorizationToken,\n });\n\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async loadPaymentsWidget(\n options: PaymentInitializeOptions & WithKlarnaV2PaymentInitializeOptions,\n ): Promise {\n if (!options.klarnav2) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarnav2\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n gatewayId,\n klarnav2: { container, onLoad },\n } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const params = { params: cartId };\n\n await this.klarnav2TokenUpdater.updateClientToken(gatewayId, { params }).catch(() => {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n });\n\n return new Promise((resolve) => {\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!this.klarnaPayments || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.klarnaPayments.init({ client_token: paymentMethod.clientToken });\n this.klarnaPayments.load(\n { container, payment_method_category: paymentMethod.id },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this.mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this.needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(methodId: string): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const shippingAddress = state.getShippingAddress();\n\n const updateSessionData = this.getUpdateSessionData(billingAddress, shippingAddress);\n\n return new Promise((resolve, reject) => {\n if (!this.klarnaPayments) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this.klarnaPayments.authorize(\n { payment_method_category: methodId },\n updateSessionData,\n (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPayments from './klarna-payments';\nimport KlarnaV2Window from './klarnav2-window';\n\nconst SDK_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js';\n\nexport default class KlarnaV2ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private klarnaWindow: KlarnaV2Window = window,\n ) {}\n\n async load(): Promise {\n if (!this.klarnaWindow.Klarna?.Payments) {\n await this.scriptLoader.loadScript(SDK_URL);\n }\n\n if (!this.klarnaWindow.Klarna?.Payments) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.klarnaWindow.Klarna.Payments;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n PaymentMethod,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class KlarnaV2TokenUpdater {\n constructor(private requestSender: RequestSender) {}\n\n updateClientToken(\n gatewayId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${gatewayId}`;\n\n return this.requestSender.get(url, {\n timeout,\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n async klarnaOrderInitialization(\n cartId: string,\n clientToken: string | undefined,\n ): Promise {\n const url = `/api/storefront/initialization/klarna`;\n const options = {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n cartId,\n clientToken,\n },\n };\n\n await this.requestSender.put(url, options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaV2PaymentStrategy from './klarnav2-payment-strategy';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nconst createKlarnaV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const requestSender = createRequestSender({ host: getHost() });\n\n return new KlarnaV2PaymentStrategy(\n paymentIntegrationService,\n new KlarnaV2ScriptLoader(getScriptLoader()),\n new KlarnaV2TokenUpdater(requestSender),\n );\n};\n\nexport default toResolvableModule(createKlarnaV2PaymentStrategy, [{ gateway: 'klarna' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class LegacyPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(payload, options);\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport LegacyPaymentStrategy from './legacy-payment-strategy';\n\nconst createLegacyPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new LegacyPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createLegacyPaymentStrategy, [{ id: 'testgateway' }]);\n","import { each, some } from 'lodash';\n\nimport {\n getBrowserInfo,\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { MollieClient, MollieElement } from './mollie';\nimport MolliePaymentInitializeOptions, {\n WithMolliePaymentInitializeOptions,\n} from './mollie-payment-initialize-options';\nimport MollieScriptLoader from './mollie-script-loader';\n\nexport enum MolliePaymentMethodType {\n CREDIT_CARD = 'credit_card',\n}\n\nconst methodsNotAllowedWhenDigitalOrder = ['klarnapaylater', 'klarnasliceit'];\n\nexport default class MolliePaymentStrategy implements PaymentStrategy {\n private initializeOptions?: MolliePaymentInitializeOptions;\n private mollieClient?: MollieClient;\n private cardHolderElement?: MollieElement;\n private cardNumberElement?: MollieElement;\n private verificationCodeElement?: MollieElement;\n private expiryDateElement?: MollieElement;\n private locale?: string;\n\n private hostedForm?: HostedForm;\n\n private unsubscribe?: () => void;\n\n constructor(\n private mollieScriptLoader: MollieScriptLoader,\n private paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithMolliePaymentInitializeOptions,\n ): Promise {\n const { mollie, methodId, gatewayId } = options;\n\n if (!mollie) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.mollie\" argument is not provided.',\n );\n }\n\n if (!methodId || !gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" and/or \"gatewayId\" argument is not provided.',\n );\n }\n\n const controllers = document.querySelectorAll('.mollie-components-controller');\n\n each(controllers, (controller) => controller.remove());\n\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n\n this.initializeOptions = mollie;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n const {\n config: { merchantId, testMode },\n } = paymentMethod;\n\n this.locale = state.getLocale();\n\n if (!merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this.isCreditCard(methodId) &&\n mollie.form &&\n this.shouldShowTSVHostedForm(methodId, gatewayId)\n ) {\n this.hostedForm = await this.mountCardVerificationfields(mollie.form);\n } else if (this.isCreditCard(methodId)) {\n this.mollieClient = await this.loadMollieJs(\n merchantId,\n storeConfig.storeProfile.storeLanguage,\n testMode,\n );\n this.mountElements();\n }\n\n this.unsubscribe = () => {\n if (\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const element = document.getElementById(`${gatewayId}-${methodId}-paragraph`);\n\n if (element) {\n element.remove();\n }\n\n mollie.disableButton(false);\n\n this.loadPaymentMethodsAllowed(mollie, methodId, gatewayId);\n }\n };\n\n this.unsubscribe();\n\n this.loadPaymentMethodsAllowed(mollie, methodId, gatewayId);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !payment.gatewayId || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment', 'gatewayId', 'paymentData']);\n }\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n return await this.executeWithVaulted(payment);\n }\n\n if (this.isCreditCard(payment.methodId)) {\n return await this.executeWithCC(payment);\n }\n\n return await this.executeWithAPM(payment);\n } catch (error) {\n await this.processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(options?: PaymentRequestOptions): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n if (options && options.methodId && options.gatewayId && !this.hostedForm) {\n const element = document.getElementById(`${options.gatewayId}-${options.methodId}`);\n\n if (element) {\n element.remove();\n }\n } else if (options && options.methodId && this.isCreditCard(options.methodId)) {\n if (\n this.cardHolderElement &&\n this.cardNumberElement &&\n this.verificationCodeElement &&\n this.expiryDateElement\n ) {\n this.cardHolderElement.unmount();\n this.cardHolderElement = undefined;\n\n this.cardNumberElement.unmount();\n this.cardNumberElement = undefined;\n\n this.verificationCodeElement.unmount();\n this.verificationCodeElement = undefined;\n\n this.expiryDateElement.unmount();\n this.expiryDateElement = undefined;\n }\n }\n\n this.mollieClient = undefined;\n\n return Promise.resolve();\n }\n\n protected async executeWithCC(payment: OrderPaymentRequestBody): Promise {\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { token, error } = await this.getMollieClient().createToken();\n\n /* eslint-disable */\n if (error) {\n return Promise.reject(error);\n }\n\n const formattedPayload = {\n credit_card_token: {\n token,\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n browser_info: getBrowserInfo(),\n shopper_locale: this.getShopperLocale(),\n };\n /* eslint-enable */\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload,\n },\n });\n }\n\n protected async executeWithVaulted(payment: OrderPaymentRequestBody): Promise {\n if (this.isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) {\n const form = this.hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n await this.paymentIntegrationService.loadCurrentOrder();\n } else {\n await this.paymentIntegrationService.submitPayment(payment);\n }\n }\n\n protected async executeWithAPM(payment: OrderPaymentRequestBody): Promise {\n const paymentData = payment.paymentData;\n const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : '';\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: {\n issuer,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n shopper_locale: this.getShopperLocale(),\n },\n },\n });\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === MolliePaymentMethodType.CREDIT_CARD;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this.isHostedPaymentFormEnabled(methodId, gatewayId) && this.isHostedFieldAvailable()\n );\n }\n\n private mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n /* eslint-disable */\n return new Promise(async (resolve, reject) => {\n try {\n const config = this.paymentIntegrationService.getState().getStoreConfig();\n const bigpayBaseUrl = config?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this.paymentIntegrationService.createHostedForm(\n bigpayBaseUrl,\n formOptions\n );\n\n await form.attach();\n\n resolve(form);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n private isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n\n return !!options.form?.fields;\n }\n\n private processAdditionalAction(error: any): Promise {\n if (!isRequestError(error)) {\n return Promise.reject(error);\n }\n\n if (some(error.body.errors, {code: 'additional_action_required'})) {\n const { additional_action_required: { data : { redirect_url } } } = error.body;\n\n return new Promise(() => window.location.replace(redirect_url));\n }\n\n return Promise.reject(error);\n }\n\n private getInitializeOptions(): MolliePaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private loadMollieJs(merchantId: string, locale: string, testmode = false): Promise {\n if (this.mollieClient) {\n return Promise.resolve(this.mollieClient);\n }\n\n return this.mollieScriptLoader\n .load(merchantId, locale, testmode);\n }\n\n private getMollieClient(): MollieClient {\n if (!this.mollieClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.mollieClient;\n }\n\n private getShopperLocale(): string {\n if (!this.locale) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.locale;\n }\n\n /**\n * ContainerId is use in Mollie for determined either its showing or not the\n * container, because when Mollie has Vaulted Instruments it gets hide,\n * and shows an error because can't mount Provider Components\n *\n * We had to add a settimeout because Mollie sets de tab index after mounting\n * each component, but without a setTimeOut Mollie is not able to find the\n * components as they are hidden so we need to wait until they are shown\n */\n private mountElements() {\n const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this.getInitializeOptions();\n let container: HTMLElement | null;\n\n if (containerId) {\n container = document.getElementById(containerId);\n }\n\n setTimeout(() => {\n if (!containerId || container?.style.display !== 'none') {\n const mollieClient = this.getMollieClient();\n\n this.cardHolderElement = mollieClient.createComponent('cardHolder', { styles });\n this.cardHolderElement.mount(`#${cardHolderId}`);\n\n this.cardNumberElement = mollieClient.createComponent('cardNumber', { styles });\n this.cardNumberElement.mount(`#${cardNumberId}`);\n\n this.verificationCodeElement = mollieClient.createComponent('verificationCode', { styles });\n this.verificationCodeElement.mount(`#${cardCvcId}`);\n\n this.expiryDateElement = mollieClient.createComponent('expiryDate', { styles });\n this.expiryDateElement.mount(`#${cardExpiryId}`);\n }\n }, 0);\n }\n\n private loadPaymentMethodsAllowed(mollie: MolliePaymentInitializeOptions, methodId: string, gatewayId: string){\n if (methodsNotAllowedWhenDigitalOrder.includes(methodId)) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const cartDigitalItems = cart.lineItems?.digitalItems;\n\n if (cartDigitalItems && cartDigitalItems.length > 0) {\n const { containerId } = this.getInitializeOptions();\n\n if (containerId) {\n const container = document.getElementById(containerId);\n\n if (container) {\n const paragraph = document.createElement('p') ;\n paragraph.setAttribute(\"id\",`${gatewayId}-${methodId}-paragraph`)\n\n if (mollie.unsupportedMethodMessage) {\n paragraph.innerText = mollie.unsupportedMethodMessage;\n container.appendChild(paragraph);\n mollie.disableButton(true);\n }\n }\n }\n }\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isMollieWindow from './is-mollie-window';\nimport { MollieClient } from './mollie';\n\nexport default class MollieScriptLoader {\n constructor(private scriptLoader: ScriptLoader, private mollieHostWindow: Window = window) {}\n\n async load(merchantId: string, locale: string, testmode: boolean): Promise {\n await this.scriptLoader.loadScript('https://js.mollie.com/v1/mollie.js');\n\n if (!isMollieWindow(this.mollieHostWindow)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.mollieHostWindow.Mollie(merchantId, {\n locale,\n testmode,\n });\n }\n}\n","import { MollieHostWindow } from './mollie';\n\nexport default function isMollieWindow(window: Window): window is MollieHostWindow {\n return 'Mollie' in window;\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MolliePaymentStrategy from './mollie-payment-strategy';\nimport MollieScriptLoader from './mollie-script-loader';\n\nconst createMolliePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new MolliePaymentStrategy(\n new MollieScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n );\n};\n\nexport default toResolvableModule(createMolliePaymentStrategy, [\n { gateway: 'mollie' },\n { gateway: 'mollie', id: 'applepay' },\n]);\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { isEmpty, map, omitBy } from 'lodash';\n\nimport {\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MonerisStylingProps, {\n MoneriesHostedFieldsQueryParams,\n MonerisInitializationData,\n MonerisResponseData,\n} from './moneris';\nimport MonerisPaymentInitializeOptions, {\n WithMonerisPaymentInitializeOptions,\n} from './moneris-payment-initialize-options';\n\nconst IFRAME_NAME = 'moneris-payment-iframe';\nconst RESPONSE_SUCCESS_CODE = '001';\n\nexport default class MonerisPaymentStrategy {\n private iframe?: HTMLIFrameElement;\n private initializeOptions?: MonerisPaymentInitializeOptions;\n private windowEventListener?: (response: MessageEvent) => void;\n\n private hostedForm?: HostedForm;\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithMonerisPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n const { moneris: monerisOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" argument is not provided.',\n );\n }\n\n if (!monerisOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.moneris\" argument is not provided.',\n );\n }\n\n this.initializeOptions = monerisOptions;\n\n const { config, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!initializationData?.profileId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (monerisOptions.form && this.shouldShowTSVHostedForm(methodId)) {\n this.hostedForm = await this.mountCardVerificationfields(monerisOptions.form);\n }\n\n if (!this.iframe) {\n this.iframe = this.createIframe(\n monerisOptions.containerId,\n initializationData,\n !!config.testMode,\n );\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentInitializeOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n await this.executeWithVaulted(payment);\n\n return;\n }\n\n return this.executeWithCC(payment);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n if (this.windowEventListener) {\n window.removeEventListener('message', this.windowEventListener);\n this.windowEventListener = undefined;\n }\n\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n this.iframe = undefined;\n }\n\n return Promise.resolve();\n }\n\n private async executeWithCC(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(payment.methodId);\n\n const testMode = paymentMethod.config.testMode;\n const paymentData = payment.paymentData || {};\n const instrumentSettings = isHostedInstrumentLike(paymentData)\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = instrumentSettings;\n\n const nonce = await new Promise((resolve, reject) => {\n if (!this.iframe) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const frameref: Window | null = this.iframe.contentWindow;\n\n if (frameref === null) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n frameref.postMessage('tokenize', this.monerisURL(!!testMode));\n\n this.windowEventListener = (response: MessageEvent) => {\n if (typeof response.data !== 'string') {\n return;\n }\n\n try {\n resolve(this.handleMonerisResponse(response));\n } catch (error) {\n reject(error);\n }\n };\n\n window.addEventListener('message', this.windowEventListener);\n });\n\n if (nonce !== undefined) {\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: { nonce, shouldSaveInstrument, shouldSetAsDefaultInstrument },\n });\n }\n }\n\n private async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this.hostedForm) {\n const form = this.hostedForm;\n\n await form.validate();\n await form.submit(payment);\n\n return this.paymentIntegrationService.loadCurrentOrder();\n }\n\n return this.paymentIntegrationService.submitPayment(payment);\n }\n\n private shouldShowTSVHostedForm(methodId: string): boolean {\n return this.isHostedPaymentFormEnabled(methodId) && this.isHostedFieldAvailable();\n }\n\n private isHostedPaymentFormEnabled(methodId: string): boolean {\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private getInitializeOptions(): MonerisPaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private async mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n const bigpayBaseUrl = this.paymentIntegrationService.getState().getStoreConfig()\n ?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this.paymentIntegrationService.createHostedForm(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private createIframe(\n containerId: string,\n initializationData: MonerisInitializationData,\n testMode: boolean,\n style?: MonerisStylingProps,\n ): HTMLIFrameElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError('Unable to create iframe without valid container ID.');\n }\n\n const iframe: HTMLIFrameElement = document.createElement('iframe');\n const monerisQueryParams: MoneriesHostedFieldsQueryParams = {\n id: initializationData.profileId,\n pmmsg: true,\n display_labels: 1,\n enable_exp: 1,\n enable_cvd: 1,\n css_body:\n style?.cssBody ||\n 'font-family: Arial, Helvetica,sans-serif;background: transparent;',\n css_textbox:\n style?.cssTextbox ||\n 'border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;',\n css_textbox_pan: style?.cssTextboxCardNumber || 'width: 240px;',\n css_textbox_exp:\n style?.cssTextboxExpiryDate || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_textbox_cvd: style?.cssTextboxCVV || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_input_label:\n style?.cssInputLabel ||\n 'font-size: 10px;position: relative;top: 8px;left: 6px;background: rgb(255,255,255);padding: 3px 2px;color: rgb(66,66,66);font-weight: 600;z-index: 2;',\n pan_label: initializationData.creditCardLabel || 'Credit Card Number',\n exp_label: initializationData.expiryDateLabel || 'Expiration',\n cvd_label: initializationData.cvdLabel || 'CVD',\n };\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const queryString = map(monerisQueryParams, (value, key) => `${key}=${value}`).join('&');\n\n iframe.width = '100%';\n iframe.height = '100%';\n iframe.name = IFRAME_NAME;\n iframe.id = IFRAME_NAME;\n iframe.style.border = 'none';\n iframe.src = `${this.monerisURL(testMode)}?${queryString}`;\n\n container.appendChild(iframe);\n\n return iframe;\n }\n\n private handleMonerisResponse(response: MessageEvent): string {\n const monerisResponse: MonerisResponseData = JSON.parse(response.data);\n\n if (monerisResponse.responseCode[0] !== RESPONSE_SUCCESS_CODE) {\n throw new Error(monerisResponse.errorMessage);\n }\n\n return monerisResponse.dataKey;\n }\n\n private monerisURL(testMode: boolean): string {\n return `https://${testMode ? 'esqa' : 'www3'}.moneris.com/HPPtoken/index.php`;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MonerisPaymentStrategy from './moneris-payment-strategy';\n\nconst createMonerisPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new MonerisPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createMonerisPaymentStrategy, [{ id: 'moneris' }]);\n","import { omit } from 'lodash';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class NoPaymentDataRequiredPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(omit(payload, 'payment'), options);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport NoPaymentDataRequiredPaymentStrategy from './no-payment-data-required-strategy';\n\nconst createNoPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new NoPaymentDataRequiredPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createNoPaymentStrategy, [{ id: 'nopaymentdatarequired' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OfflinePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment ? { methodId: payload.payment.methodId } : undefined,\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OfflinePaymentStrategy from './offline-payment-strategy';\n\nconst createOfflinePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OfflinePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOfflinePaymentStrategy, [{ type: 'PAYMENT_TYPE_OFFLINE' }]);\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OffsitePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const orderPayload = this._shouldSubmitFullPayload(payment) ? payload : order;\n const paymentData = payment && payment.paymentData;\n const instrumentId =\n (paymentData && isVaultedInstrument(paymentData) && paymentData.instrumentId) ||\n undefined;\n const shouldSaveInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSaveInstrument) ||\n undefined;\n const shouldSetAsDefaultInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSetAsDefaultInstrument) ||\n undefined;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n await this._paymentIntegrationService.submitOrder(orderPayload, options);\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId,\n gatewayId,\n instrumentId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _shouldSubmitFullPayload(payment?: OrderPaymentRequestBody): boolean {\n // FIXME: A temporary workaround to support offsite payment methods\n // where their return URL needs to be provided by the core app.\n if (!payment) {\n return false;\n }\n\n return (\n payment.gatewayId === 'adyen' ||\n payment.gatewayId === 'barclaycard' ||\n payment.methodId === 'ccavenuemars'\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OffsitePaymentStrategy from './offsite-payment-strategy';\n\nconst createOffsitePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OffsitePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOffsitePaymentStrategy, [{ type: 'PAYMENT_TYPE_HOSTED' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import {\n HostedInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrumentPayload,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isPaypalCommerceProviderError } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommercePaymentInitializeOptions, {\n WithPayPalCommercePaymentInitializeOptions,\n} from './paypal-commerce-payment-initialize-options';\n\nexport default class PayPalCommercePaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommercePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce } = options || {};\n\n this.paypalcommerce = paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.loadingIndicatorContainer = paypalcommerce.container.split('#')[1];\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (paypalcommerce.onInit && typeof paypalcommerce.onInit === 'function') {\n paypalcommerce.onInit(() => this.renderButton(methodId, paypalcommerce));\n }\n\n if (\n paypalcommerce.shouldRenderPayPalButtonOnInitialization === undefined ||\n paypalcommerce.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, paypalcommerce);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.paypalcommerce || {};\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const shouldHandleInstrumentDeclinedError =\n features && features['PAYPAL-3438.handling_instrument_declined_error_ppc'];\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, paymentData } = payment;\n\n if (this.isPayPalVaultedInstrumentPaymentData(paymentData) && !this.orderId) {\n this.orderId = await this.createOrder();\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n const paymentPayload = this.isPayPalVaultedInstrumentPaymentData(paymentData)\n ? this.prepareVaultedInstrumentPaymentPayload(methodId, this.orderId, paymentData)\n : this.preparePaymentPayload(methodId, this.orderId, paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error: unknown) {\n if (this.isProviderError(error) && shouldHandleInstrumentDeclinedError) {\n await this.paypalCommerceIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.paypalcommerce) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.paypalcommerce);\n this.handleError(new Error('INSTRUMENT_DECLINED'), onError);\n }\n\n reject();\n });\n }\n\n this.handleError(error, onError);\n\n return Promise.reject();\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n private prepareVaultedInstrumentPaymentPayload(\n methodId: string,\n paypalOrderId: string,\n paymentData: VaultedInstrument & HostedInstrument,\n ): Payment {\n const { instrumentId, shouldSetAsDefaultInstrument } = paymentData;\n\n const shouldConfirmInstrument = !this.isTrustedVaultingFlow(paymentData);\n\n if (shouldConfirmInstrument) {\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument: shouldConfirmInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n },\n },\n };\n }\n\n return {\n methodId,\n paymentData: {\n instrumentId,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n bigpay_token: {\n token: instrumentId,\n },\n },\n },\n };\n }\n\n private preparePaymentPayload(\n methodId: string,\n paypalOrderId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n ): Payment {\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n },\n },\n };\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommercePaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () => this.createOrder(),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onError: (error) => this.handleError(error, onError),\n onCancel: () => this.toggleLoadingIndicator(false),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommercePaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommercePaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleError(\n error: unknown,\n onError: PayPalCommercePaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n private async createOrder(): Promise {\n const fieldsValues = this.getFieldsValues();\n\n return this.paypalCommerceIntegrationService.createOrder('paypalcommercecheckout', {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n });\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.paypalcommerce || {};\n\n return typeof getFieldsValues === 'function' ? getFieldsValues() : undefined;\n }\n\n private isTrustedVaultingFlow(paymentData?: PaymentInstrumentPayload): boolean {\n if (paymentData && isVaultedInstrument(paymentData)) {\n const state = this.paymentIntegrationService.getState();\n\n const instruments = state.getInstruments();\n\n const { trustedShippingAddress } =\n instruments?.find(({ bigpayToken }) => bigpayToken === paymentData.instrumentId) ||\n {};\n\n return !!trustedShippingAddress;\n }\n\n return false;\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Guards\n *\n */\n private isPayPalVaultedInstrumentPaymentData(\n paymentData?: PaymentInstrumentPayload,\n ): paymentData is VaultedInstrument & HostedInstrument {\n return (\n !!paymentData && isVaultedInstrument(paymentData) && isHostedInstrumentLike(paymentData)\n );\n }\n\n private isProviderError(error: unknown): boolean {\n if (isPaypalCommerceProviderError(error)) {\n const paypalProviderError = error?.errors?.filter((e) => e.provider_error) || [];\n\n return paypalProviderError[0]?.provider_error?.code === 'INSTRUMENT_DECLINED';\n }\n\n return false;\n }\n}\n","export interface ProviderError extends Error {\n errors?: ErrorElement[];\n status?: string;\n three_ds_result?: {\n acs_url: unknown;\n payer_auth_request: unknown;\n merchant_data: unknown;\n callback_url: unknown;\n };\n}\n\nexport interface ErrorElement {\n code: string;\n message: string;\n provider_error?: {\n code: string;\n };\n}\n\nexport default function isPaypalCommerceProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-commerce-types';\n\nfunction getPaypalMessagesStylesFromBNPLConfig({\n styles,\n}: PayPalBNPLConfigurationItem): MessagesStyleOptions {\n const messagesStyles: MessagesStyleOptions = {};\n\n if (styles.color) {\n messagesStyles.color = styles.color;\n }\n\n if (styles.layout) {\n messagesStyles.layout = styles.layout;\n }\n\n if (styles['logo-type'] || styles['logo-position']) {\n messagesStyles.logo = {};\n\n if (styles['logo-type']) {\n messagesStyles.logo.type = styles['logo-type'];\n }\n\n if (styles['logo-position']) {\n messagesStyles.logo.position = styles['logo-position'];\n }\n }\n\n if (styles.ratio) {\n messagesStyles.ratio = styles.ratio;\n }\n\n if (styles['text-color'] || styles['text-size']) {\n messagesStyles.text = {};\n\n if (styles['text-color']) {\n messagesStyles.text.color = styles['text-color'];\n }\n\n if (styles['text-size']) {\n messagesStyles.text.size = +styles['text-size'];\n }\n }\n\n return messagesStyles;\n}\n\nexport default getPaypalMessagesStylesFromBNPLConfig;\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalMessagesSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditPaymentInitializeOptions, {\n WithPayPalCommerceCreditPaymentInitializeOptions,\n} from './paypal-commerce-credit-payment-initialize-options';\n\nexport default class PayPalCommerceCreditPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalCommerceSdk: PayPalCommerceSdk,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceCreditPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercecredit } = options || {};\n\n const paypalOptions = paypalcommercecredit || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n // TODO: update paypalBNPLConfiguration with empty array as default value when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const { paypalBNPLConfiguration, orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId = '', container } = paypalOptions;\n\n // TODO: remove paypalBNPLConfiguration check when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n if (paypalBNPLConfiguration && document.getElementById(bannerContainerId)) {\n const bannerConfiguration = paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // TODO: this condition can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n if (document.getElementById(bannerContainerId)) {\n const paypalMessages = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId);\n }\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalOptions: PayPalCommerceCreditPaymentInitializeOptions,\n ): void {\n if (!paypalOptions?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalOptions;\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcheckout',\n ),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.PAYLATER) {\n return;\n }\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.CREDIT) {\n throw new NotImplementedError(\n `PayPal ${fundingSource} is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceCreditPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n if (onValidate && typeof onValidate === 'function') {\n await onValidate(onValidationPassed, reject);\n }\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceCreditPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n if (submitForm && typeof submitForm === 'function') {\n submitForm();\n }\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceCreditPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration?: PayPalBNPLConfigurationItem, // TODO: this should not be optional when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n const grandTotal = checkout.outstandingBalance;\n // TODO: default style can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const style = bannerConfiguration\n ? getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration)\n : {\n layout: 'text',\n logo: {\n type: 'inline',\n },\n };\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: grandTotal,\n placement: 'payment',\n style,\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalCommerceSdk(),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditPaymentStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoPaymentInitializeOptions, {\n WithPayPalCommerceVenmoPaymentInitializeOptions,\n} from './paypal-commerce-venmo-payment-initialize-options';\n\nexport default class PayPalCommerceVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercevenmo } = options || {};\n\n const paypalOptions = paypalcommercevenmo || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommercevenmo;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmocheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n throw new NotImplementedError(\n `PayPal Venmo is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceVenmoPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceVenmoPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalApmSdk, PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const {\n gatewayId,\n methodId,\n paypalcommerce, // FIXME: this option is deprecated\n paypalcommercealternativemethods,\n } = options;\n const paypalOptions = paypalcommercealternativemethods || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { orderId, shouldRenderFields } = paymentMethod.initializationData || {};\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.paypalCommerceSdk.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, paypalOptions);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, paypalOptions);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paypalCommerceIntegrationService.submitPayment(\n methodId,\n this.orderId,\n gatewayId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalAmpsSdk = this.getPaypalAmpsSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, submitForm } = paypalOptions;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: methodId,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => paypalOptions.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, paypalOptions),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleFailure(error, onError),\n onClick: async (_, actions) =>\n paypalOptions.onValidate(actions.resolve, actions.reject),\n };\n\n this.paypalButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): Promise {\n const { onValidate } = paypalOptions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return () => Promise.resolve();\n };\n\n await onValidate(onValidationPassed, noop);\n\n const orderId = await this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n );\n\n if (this.isNonInstantPaymentMethod(methodId)) {\n const order = { useStoreCredit: false };\n const options = {\n params: {\n methodId,\n gatewayId,\n },\n };\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(methodId, orderId, gatewayId);\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceAlternativeMethodsPaymentOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: PayPalCommerceAlternativeMethodsPaymentOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Fields methods\n *\n * */\n private renderFields(\n methodId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalAmpsSdk = this.getPaypalAmpsSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const { firstName, lastName, email } = state.getBillingAddressOrThrow();\n\n const { apmFieldsContainer, apmFieldsStyles } = paypalOptions;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument should contain \"apmFieldsContainer\".',\n );\n }\n\n const fieldContainerElement = document.querySelector(apmFieldsContainer);\n\n if (fieldContainerElement) {\n fieldContainerElement.innerHTML = '';\n }\n\n const fieldsOptions = {\n fundingSource: methodId,\n style: apmFieldsStyles || {},\n fields: {\n name: {\n value: `${firstName} ${lastName}`,\n },\n email: {\n value: email,\n },\n },\n };\n\n const paypalPaymentFields = paypalAmpsSdk.PaymentFields(fieldsOptions);\n\n paypalPaymentFields.render(apmFieldsContainer);\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantAlternativePaymentMethods;\n }\n\n private getPaypalAmpsSdkOrThrow() {\n if (!this.paypalApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalApms;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommerceAlternativeMethodsPaymentStrategy from './paypal-commerce-alternative-methods-payment-strategy';\n\nconst createPayPalCommerceAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\n]);\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumber in fields &&\n HostedFieldType.CardName in fields &&\n HostedFieldType.CardExpiry in fields\n );\n}\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardVaultedFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumberVerification in fields &&\n HostedFieldType.CardCodeVerification in fields &&\n HostedFieldType.CardExpiryVerification in fields\n );\n}\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPayPalCommerceAcceleratedCheckoutCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport {\n HostedCardFieldOptions,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldStylesMap,\n HostedFieldType,\n HostedFieldValidateEventData,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInstrument,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n isCreditCardFormFields,\n isCreditCardVaultedFormFields,\n isHostedInstrumentLike,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isPayPalCommerceAcceleratedCheckoutCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n LiabilityShiftEnum,\n PayPalCommerceCardFields,\n PayPalCommerceCardFieldsConfig,\n PayPalCommerceCardFieldsOnApproveData,\n PayPalCommerceCardFieldsState,\n PayPalCommerceFields,\n PayPalCommerceHostedFieldsRenderOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCardsPaymentInitializeOptions, {\n WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n} from './paypal-commerce-credit-cards-payment-initialize-options';\n\nexport default class PayPalCommerceCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: PayPalCommerceCardFields;\n private cvvField?: PayPalCommerceFields;\n private expiryField?: PayPalCommerceFields;\n private numberField?: PayPalCommerceFields;\n private nameField?: PayPalCommerceFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercecreditcards, paypalcommerce } = options;\n const paypalCommerceInitializationOptions = paypalcommercecreditcards || paypalcommerce;\n\n const { form, onCreditCardFieldsRenderingError } =\n paypalCommerceInitializationOptions || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!form) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form\" argument is not provided.',\n );\n }\n\n this.hostedFormOptions = form;\n\n this.isCreditCardForm = isCreditCardFormFields(form.fields);\n this.isCreditCardVaultedForm =\n isCreditCardVaultedFormFields(form.fields) && !this.hasUndefinedValues();\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n if (this.shouldInitializePayPalFastlane(methodId)) {\n await this.initializePayPalFastlaneOrThrow(methodId);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n\n if (!payment || !methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.executionPaymentData = paymentData;\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.validateHostedFormOrThrow();\n await this.submitHostedForm();\n } else {\n // This condition is triggered when we pay with vaulted instrument and shipping address is truste\n const { orderId } = await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n );\n\n this.returnedOrderId = orderId;\n }\n\n const submitPaymentPayload = this.preparePaymentPayload(\n methodId,\n paymentData,\n this.returnedOrderId,\n this.returnedVaultedToken,\n );\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.cvvField?.close();\n await this.expiryField?.close();\n await this.numberField?.close();\n await this.nameField?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Submit Payment Payload preparing method\n *\n * `vaultedToken` is used when we pay with vaulted instrument (with trusted shipping address and untrusted)\n * `setupToken` is used when we pay with vaulted instrument (untrusted shipping address)\n * `orderId` is used in every case (basic card payment, trusted shipping address and untrusted)\n */\n private preparePaymentPayload(\n methodId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n orderId?: string,\n nonce?: string,\n ): Payment {\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const instrumentId =\n paymentData && isVaultedInstrument(paymentData) ? paymentData.instrumentId : undefined;\n\n const bigpay_token = omitBy(\n {\n verification_nonce: nonce,\n token: instrumentId,\n },\n isNil,\n );\n\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n instrumentId,\n formattedPayload: {\n ...(nonce || instrumentId ? { bigpay_token } : {}),\n ...(orderId ? { card_with_order: { order_id: orderId } } : {}),\n },\n },\n };\n }\n\n /**\n *\n * Card fields initialize\n *\n */\n private async initializeFields(\n formOptions: HostedFormOptions,\n onCreditCardFieldsRenderingError?: PayPalCommerceCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\n features?.['PAYPAL-4591.paypal_commerce_3ds_verification'] &&\n (liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown)\n ) {\n throw new Error();\n }\n\n return this.handleApprove({ orderID, vaultSetupToken });\n },\n onError: () => {\n throw new PaymentMethodFailedError();\n },\n inputEvents: {\n onChange: (event) => this.onChangeHandler(formOptions, event),\n onFocus: (event) => this.onFocusHandler(formOptions, event),\n onBlur: (event) => this.onBlurHandler(formOptions, event),\n onInputSubmitRequest: (event) => this.onInputSubmitRequest(formOptions, event),\n },\n ...executeCallback,\n };\n\n this.cardFields = await paypalSdk.CardFields(cardFieldsConfig);\n\n if (!this.cardFields.isEligible()) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n this.stylizeInputContainers(fields);\n\n if (isCreditCardFormFields(fields)) {\n await this.renderFields(fields);\n }\n\n if (isCreditCardVaultedFormFields(fields)) {\n await this.renderVaultedFields(fields);\n }\n } catch (error: unknown) {\n if (typeof onCreditCardFieldsRenderingError === 'function') {\n onCreditCardFieldsRenderingError(error);\n }\n }\n }\n\n /**\n *\n * Get execute callback method\n * Depends on shipping address is trusted or not we should pass to PP\n * `createVaultSetupToken` callback if address is untrusted or\n * `createOrder` if address is trusted\n *\n */\n private getExecuteCallback(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ) {\n const isVaultedForm = isCreditCardVaultedFormFields(fields);\n\n return isVaultedForm ? this.createVaultSetupTokenCallback() : this.createOrderCallback();\n }\n\n private createVaultSetupTokenCallback() {\n return {\n createVaultSetupToken: async () => {\n const { setupToken } =\n (await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n {\n ...this.getInstrumentParams(),\n setupToken: true,\n },\n )) || {};\n\n return setupToken;\n },\n };\n }\n\n private createOrderCallback() {\n return {\n createOrder: async () => {\n const { orderId } =\n (await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n )) || {};\n\n return orderId;\n },\n };\n }\n\n /**\n *\n * onApprove method\n * When submitting a form with a `submitHostedForm` method if there is no error\n * then onApprove callback is triggered and depends on the flow\n * we will receive an `orderID` if it's basic paying and `vaultSetupToken` if we are paying\n * with vaulted instrument and shipping address is untrusted\n *\n */\n private handleApprove({ orderID, vaultSetupToken }: PayPalCommerceCardFieldsOnApproveData) {\n if (orderID) {\n this.returnedOrderId = orderID;\n }\n\n if (vaultSetupToken) {\n this.returnedVaultedToken = vaultSetupToken;\n }\n }\n\n /**\n *\n * Rendering Card Fields methods\n *\n */\n private async renderFields(fieldsOptions: HostedCardFieldOptionsMap) {\n const cardFields = this.getCardFieldsOrThrow();\n\n if (fieldsOptions.cardCode?.containerId) {\n this.cvvField = cardFields.CVVField({\n placeholder: '',\n });\n await this.cvvField.render(`#${fieldsOptions.cardCode.containerId}`);\n }\n\n if (fieldsOptions.cardExpiry?.containerId) {\n this.expiryField = cardFields.ExpiryField();\n await this.expiryField.render(`#${fieldsOptions.cardExpiry.containerId}`);\n }\n\n if (fieldsOptions.cardName?.containerId) {\n this.nameField = cardFields.NameField({\n placeholder: '',\n });\n await this.nameField.render(`#${fieldsOptions.cardName.containerId}`);\n }\n\n if (fieldsOptions.cardNumber?.containerId) {\n this.numberField = cardFields.NumberField({\n placeholder: '',\n });\n await this.numberField.render(`#${fieldsOptions.cardNumber.containerId}`);\n }\n }\n\n private async renderVaultedFields(fieldsOptions: HostedStoredCardFieldOptionsMap) {\n const cardFields = this.getCardFieldsOrThrow();\n\n if (fieldsOptions.cardCodeVerification?.containerId) {\n this.cvvField = cardFields.CVVField({\n placeholder: '',\n });\n await this.cvvField.render(`#${fieldsOptions.cardCodeVerification.containerId}`);\n }\n\n if (fieldsOptions.cardExpiryVerification?.containerId) {\n this.expiryField = cardFields.ExpiryField();\n await this.expiryField.render(`#${fieldsOptions.cardExpiryVerification.containerId}`);\n }\n\n if (fieldsOptions.cardNumberVerification?.containerId) {\n this.numberField = cardFields.NumberField({\n placeholder: '',\n });\n await this.numberField.render(`#${fieldsOptions.cardNumberVerification.containerId}`);\n }\n }\n\n /**\n *\n * Instrument params method\n *\n */\n private getInstrumentParams(): HostedInstrument | VaultedInstrument {\n if (!this.executionPaymentData) {\n return {};\n }\n\n if (isHostedInstrumentLike(this.executionPaymentData)) {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } =\n this.executionPaymentData;\n\n return {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n if (isVaultedInstrument(this.executionPaymentData)) {\n const { instrumentId } = this.executionPaymentData;\n\n return {\n instrumentId,\n };\n }\n\n return {};\n }\n\n private getFieldTypeByEmittedField({\n emittedBy,\n }: PayPalCommerceCardFieldsState):\n | HostedFieldBlurEventData\n | HostedFieldEnterEventData\n | HostedFieldFocusEventData {\n return {\n fieldType: this.mapFieldType(emittedBy),\n };\n }\n\n /**\n *\n * Form submit method\n * Triggers a form submit\n * */\n private async submitHostedForm() {\n const cardFields = this.getCardFieldsOrThrow();\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const submitConfig = {\n billingAddress: {\n company: billingAddress.company,\n addressLine1: billingAddress.address1,\n addressLine2: billingAddress.address2,\n adminArea1: billingAddress.stateOrProvinceCode,\n adminArea2: billingAddress.city,\n postalCode: billingAddress.postalCode,\n countryCode: billingAddress.countryCode,\n },\n };\n\n try {\n if (this.isCreditCardVaultedForm) {\n await cardFields.submit();\n } else {\n await cardFields.submit(submitConfig);\n }\n } catch (_) {\n throw new PaymentMethodFailedError(\n 'Failed authentication. Please try to authorize again.',\n );\n }\n }\n\n /**\n *\n * Validation and errors\n *\n */\n private async validateHostedFormOrThrow() {\n const cardFields = this.getCardFieldsOrThrow();\n const cardFieldsState = await cardFields.getState().then((data) => data);\n const validationData = this.getValidityData(cardFieldsState);\n\n if (validationData.isValid) {\n return;\n }\n\n this.hostedFormOptions?.onValidate?.(validationData);\n\n throw new PaymentInvalidFormError(this.mapValidationErrors(validationData.errors));\n }\n\n private getValidityData({\n fields,\n }: PayPalCommerceCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof PayPalCommerceCardFieldsState['fields']\n >;\n\n const isValid = fieldsKeys.every((key) => updatedFields[key]?.isValid);\n\n const errors = fieldsKeys.reduce((fieldsErrors, key) => {\n const fieldType = this.mapFieldType(key);\n\n return {\n ...fieldsErrors,\n [fieldType]: updatedFields[key]?.isValid\n ? undefined\n : [this.getInvalidErrorByFieldType(fieldType)],\n };\n }, {});\n\n return { isValid, errors };\n }\n\n private getInvalidErrorByFieldType(fieldType: string): HostedInputValidateErrorData {\n switch (fieldType) {\n case HostedFieldType.CardCode:\n case HostedFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case HostedFieldType.CardNumber:\n case HostedFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case HostedFieldType.CardExpiry:\n case HostedFieldType.CardExpiryVerification:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private mapValidationErrors(\n validationErrors: HostedInputValidateErrorDataMap = {},\n ): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n const validationErrorsKeys = Object.keys(validationErrors) as Array<\n keyof HostedInputValidateErrorDataMap\n >;\n\n validationErrorsKeys.forEach((key) => {\n errors[key] = [\n {\n message: validationErrors[key]?.[0]?.message || '',\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n /**\n *\n * Fields mappers\n *\n */\n private mapFieldType(type: string): HostedFieldType {\n switch (type) {\n case 'name':\n return HostedFieldType.CardName;\n\n case 'cardNumberField':\n case 'number':\n return this.isCreditCardForm\n ? HostedFieldType.CardNumber\n : HostedFieldType.CardNumberVerification;\n\n case 'cardExpiryField':\n case 'expiry':\n return this.isCreditCardForm\n ? HostedFieldType.CardExpiry\n : HostedFieldType.CardExpiryVerification;\n\n case 'cardCvvField':\n case 'cvv':\n return this.isCreditCardForm\n ? HostedFieldType.CardCode\n : HostedFieldType.CardCodeVerification;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n /**\n *\n * Utils\n *\n */\n private getCardFieldsOrThrow(): PayPalCommerceCardFields {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.cardFields;\n }\n\n private getInputStyles(\n styles?: HostedFieldStylesMap,\n ): PayPalCommerceHostedFieldsRenderOptions['styles'] {\n const commonStyles = {\n 'font-size': styles?.default?.fontSize || '1rem',\n 'font-family':\n styles?.default?.fontFamily || 'Montserrat, Arial, Helvetica, sans-serif',\n 'font-weight': styles?.default?.fontWeight || '400',\n outline: 'none',\n padding: '9px 13px',\n };\n\n const defaultStyles = { ...commonStyles, color: '#333333' };\n const errorStyles = { ...commonStyles, color: 'red' };\n\n return {\n input: defaultStyles,\n '.invalid': errorStyles,\n '.valid': defaultStyles,\n ':focus': defaultStyles,\n };\n }\n\n private stylizeInputContainers(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ): void {\n Object.values(fields || {}).forEach((id: HostedCardFieldOptions) => {\n const element = document.getElementById(`${id?.containerId || ''}`);\n\n if (element) {\n element.style.padding = '0px';\n element.style.boxShadow = 'none';\n element.style.border = 'none';\n element.style.background = 'transparent';\n element.style.marginBottom = '10px';\n element.style.marginLeft = '-5px';\n }\n });\n }\n\n private hasUndefinedValues() {\n if (this.hostedFormOptions) {\n return Object.values(this.hostedFormOptions.fields).some(\n (value) => value === undefined,\n );\n }\n\n return true;\n }\n\n /**\n *\n * Input events methods\n *\n */\n private onChangeHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * PayPal Commerce Accelerated checkout related methods\n *\n */\n // TODO: remove this part when PPCP AXO A/B testing will be finished\n private shouldInitializePayPalFastlane(methodId: string) {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalCommercePaymentProviderCustomer = isPayPalCommerceAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isPayPalCommerceAnalyticsV2Enabled &&\n !paypalCommercePaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when PPCP AXO A/B testing will be finished\n private async initializePayPalFastlaneOrThrow(methodId: string): Promise {\n try {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n payPalFastlaneSdk,\n !!initializationData?.isDeveloperModeApplicable,\n );\n } catch (_: unknown) {\n // We should avoid throwing any error from this flow to do no brake default flow\n // This flow is optional\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\n]);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n BirthDate,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport {\n PaypalCommerceRatePay,\n WithPayPalCommerceRatePayPaymentInitializeOptions,\n} from './paypal-commerce-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PaypalCommerceRatepayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private paypalcommerceratepay?: PaypalCommerceRatePay;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private pollingInterval: number = POLLING_INTERVAL,\n private maxPollingIntervalTime: number = MAX_POLLING_TIME,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, paypalcommerceratepay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerceratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerceratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = paypalcommerceratepay;\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.container\" argument is not provided.`,\n );\n }\n\n if (!legalTextContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.legalTextContainer\" argument is not provided.`,\n );\n }\n\n if (!loadingContainerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.loadingContainerId\" argument is not provided.`,\n );\n }\n\n this.loadingIndicatorContainer = loadingContainerId;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { merchantId } = paymentMethod.initializationData || {};\n\n if (!merchantId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because merchantId argument is not provided.`,\n );\n }\n\n this.paypalcommerceratepay = paypalcommerceratepay;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.createFraudNetScript(merchantId, methodId, gatewayId);\n\n this.loadFraudnetConfig();\n\n this.renderLegalText(legalTextContainer, container);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n const { getFieldsValues } = this.paypalcommerceratepay || {};\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!getFieldsValues || typeof getFieldsValues !== 'function') {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.getFieldsValues\" argument is not provided.`,\n );\n }\n\n this.toggleLoadingIndicator(true);\n\n try {\n const orderId = await this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n { metadataId: this.guid },\n );\n\n const { ratepayBirthDate, ratepayPhoneNumber, ratepayPhoneCountryCode } =\n getFieldsValues();\n\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: payment.methodId,\n rate_pay: {\n birth_date: this.normalizeDate(ratepayBirthDate),\n phone: {\n national_number: ratepayPhoneNumber,\n country_code: ratepayPhoneCountryCode.split('+')[1],\n },\n },\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n\n return await new Promise((resolve, reject) => {\n this.initializePollingMechanism(\n payment.methodId,\n resolve,\n reject,\n payment.gatewayId,\n );\n });\n } catch (error: unknown) {\n this.handleError(error);\n\n return new Promise((_resolve, reject) => reject());\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const { legalTextContainer } = this.paypalcommerceratepay || {};\n const fraudNetScript = document.querySelectorAll('[data-id=\"fraudnetScript\"]')[0];\n const fraudNetConfig = document.querySelectorAll('[data-id=\"fraudnetConfig\"]')[0];\n\n this.deinitializePollingMechanism();\n\n fraudNetScript.remove();\n fraudNetConfig.remove();\n\n if (legalTextContainer) {\n const legalTextContainerElement = document.getElementById(legalTextContainer);\n\n legalTextContainerElement?.remove();\n }\n\n return Promise.resolve();\n }\n\n private normalizeDate(date: BirthDate) {\n const formattedDate = this.formatDate(date.getDate());\n const formattedMonth = this.formatDate(date.getMonth() + 1);\n\n return `${date.getFullYear()}-${formattedMonth}-${formattedDate}`;\n }\n\n private formatDate(date: number): string {\n return `${date < 10 ? 0 : ''}${date}`;\n }\n\n private renderLegalText(legalTextContainerElementId: string, container: string) {\n const legalTextContainerId = legalTextContainerElementId;\n const buttonContainerId = container.split('#')[1];\n const buttonContainer = document.getElementById(buttonContainerId);\n const buttonContainerParent = buttonContainer?.parentNode;\n const legalTextContainer = document.createElement('div');\n\n legalTextContainer.style.marginBottom = '20px';\n legalTextContainer.setAttribute('id', legalTextContainerId);\n buttonContainerParent?.prepend(legalTextContainer);\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = paypalSdk.Legal({\n fundingSource: paypalSdk.Legal.FUNDING.PAY_UPON_INVOICE,\n });\n const legalTextContainerElement = document.getElementById(legalTextContainerId);\n\n if (legalTextContainerElement) {\n ratePayButton.render(`#${legalTextContainerId}`);\n } else {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"legalTextContainerElement\" argument is not found.`,\n );\n }\n }\n\n private handleError(error: unknown): void {\n const { onError } = this.paypalcommerceratepay || {};\n\n this.resetPollingMechanism();\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n private createFraudNetScript(merchantId: string, methodId: string, gatewayId: string) {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { testMode } = paymentMethod.config;\n const scriptElement = document.createElement('script');\n\n scriptElement.setAttribute('type', 'application/json');\n scriptElement.setAttribute('fncls', 'fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99');\n scriptElement.setAttribute('data-id', 'fraudnetScript');\n this.guid = this.generateGUID();\n\n const fraudNetConfig = {\n f: this.guid,\n s: `${merchantId}_checkout-page`,\n sandbox: testMode,\n };\n\n scriptElement.innerHTML = JSON.stringify(fraudNetConfig);\n document.body.appendChild(scriptElement);\n }\n\n private generateGUID() {\n let guid = '';\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n for (let i = 0; i < 32; i += 1) {\n const randomIndex = Math.floor(Math.random() * characters.length);\n\n guid += characters[randomIndex];\n }\n\n return guid;\n }\n\n private loadFraudnetConfig() {\n const script = document.createElement('script');\n\n script.setAttribute('data-id', 'fraudnetConfig');\n script.src = 'https://c.paypal.com/da/r/fb.js';\n document.body.appendChild(script);\n }\n\n private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithPayPalCommerceRatePayPaymentInitializeOptions,\n ): Promise {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: () => void,\n rejectPromise: () => void,\n gatewayId?: string,\n ): Promise {\n await new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, this.pollingInterval);\n\n this.stopPolling = () => {\n clearTimeout(timeout);\n this.toggleLoadingIndicator(false);\n\n return reject();\n };\n });\n\n try {\n this.pollingTimer += this.pollingInterval;\n\n const orderStatus = await this.paypalCommerceIntegrationService.getOrderStatus(\n 'paypalcommercealternativemethods',\n {\n params: {\n useMetadata: true,\n },\n },\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.PollingStop;\n const isPollingError = orderStatus === PayPalOrderStatus.PollingError;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (!isOrderApproved && this.pollingTimer < this.maxPollingIntervalTime) {\n return await this.initializePollingMechanism(\n methodId,\n resolvePromise,\n rejectPromise,\n gatewayId,\n );\n }\n\n await this.reinitializeStrategy({\n methodId,\n gatewayId,\n paypalcommerceratepay: this.paypalcommerceratepay,\n });\n\n this.handleError(new TimeoutError());\n } catch (error) {\n this.handleError(error);\n rejectPromise();\n }\n }\n\n private deinitializePollingMechanism(): void {\n this.stopPolling();\n this.pollingTimer = 0;\n }\n\n private resetPollingMechanism(): void {\n this.deinitializePollingMechanism();\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createPaypalCommerceRatepayPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods', id: 'ratepay' },\n]);\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n// TODO: update PayPalConnectCustomer with PayPalFastlaneCustomer\nexport default function isPayPalFastlaneCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import {\n CardInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\n\nimport { WithPayPalCommerceFastlanePaymentInitializeOptions } from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n // TODO: remove paypalcommerceacceleratedcheckout if it was removed on checkout js side\n const { methodId, paypalcommercefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercefastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane\" argument is not provided.',\n );\n }\n\n if (!paypalcommercefastlane.onInit || typeof paypalcommercefastlane.onInit !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !paypalcommercefastlane.onChange ||\n typeof paypalcommercefastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane.onChange\" argument is not provided or it is not a function.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n const paypalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n const paypalFastlaneStyling = isFastlaneStylingEnabled\n ? paymentMethod?.initializationData?.fastlaneStyles\n : {};\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStyling,\n paypalcommercefastlane?.styles,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n paypalcommercefastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n paypalcommercefastlane.onChange(() => this.handlePayPalStoredInstrumentChange(methodId));\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n // TODO: we should probably update this method with removeStorageSessionId for better reading experience\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(true);\n } catch (error) {\n if (error instanceof Error && error.name !== 'FastlaneError') {\n throw error;\n }\n\n return Promise.reject();\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n /**\n *\n * Authentication flow methods\n *\n */\n private shouldRunAuthenticationFlow(): boolean {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const paypalFastlaneSessionId = this.paypalCommerceFastlaneUtils.getStorageSessionId();\n\n if (\n !customer.isGuest ||\n paypalFastlaneCustomer?.authenticationState ===\n PayPalFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return !paypalFastlaneCustomer?.authenticationState && paypalFastlaneSessionId === cart.id;\n }\n\n private async runPayPalAuthenticationFlowOrThrow(methodId: string): Promise {\n try {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const customerEmail = customer?.email || billingAddress?.email || '';\n\n const { customerContextId } =\n await this.paypalCommerceFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState ===\n PayPalFastlaneAuthenticationState.CANCELED;\n\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cart.id,\n );\n } catch (error) {\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n }\n\n /**\n *\n * PayPal Fastlane Card Component rendering method\n *\n */\n private async initializePayPalPaymentComponent(): Promise {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const phone = billingAddress.phone;\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`.trim();\n\n const paypalFastlane = this.paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const cardComponentOptions: PayPalFastlaneCardComponentOptions = {\n fields: {\n cardholderName: {\n prefill: fullName,\n enabled: true,\n },\n ...(phone && {\n phoneNumber: {\n prefill: phone,\n },\n }),\n },\n };\n\n this.paypalComponentMethods = await paypalFastlane.FastlaneCardComponent(\n cardComponentOptions,\n );\n }\n\n private renderPayPalPaymentComponent(container?: string): void {\n const paypalComponentMethods = this.getPayPalComponentMethodsOrThrow();\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render card component because \"container\" argument is not provided.',\n );\n }\n\n paypalComponentMethods.render(container);\n }\n\n private getPayPalComponentMethodsOrThrow(): PayPalFastlaneCardComponentMethods {\n if (!this.paypalComponentMethods) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalComponentMethods;\n }\n\n /**\n *\n * Payment Payload preparation methods\n *\n */\n private async prepareVaultedInstrumentPaymentPayload(\n methodId: string,\n paymentData: VaultedInstrument,\n ): Promise> {\n const { instrumentId } = paymentData;\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(methodId, {\n cartId,\n });\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: orderId,\n token: instrumentId,\n },\n },\n },\n };\n }\n\n private async preparePaymentPayload(\n methodId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n ): Promise> {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const billingAddress = state.getBillingAddressOrThrow();\n\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`.trim();\n\n const { getPaymentToken } = this.getPayPalComponentMethodsOrThrow();\n\n const { id } = await getPaymentToken({\n name: { fullName },\n billingAddress: this.paypalCommerceFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(methodId, {\n cartId,\n });\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: orderId,\n token: id,\n },\n },\n },\n };\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const { selectionChanged, selectedCard } = await paypalAxoSdk.profile.showCardSelector();\n\n if (selectionChanged) {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const selectedInstrument = this.paypalCommerceFastlaneUtils.mapPayPalToBcInstrument(\n methodId,\n selectedCard,\n )[0];\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n ...paypalFastlaneCustomer,\n instruments: [selectedInstrument],\n });\n\n return selectedInstrument;\n }\n\n return undefined;\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\n\nimport PayPalCommerceFastlanePaymentStrategy from './paypal-commerce-fastlane-payment-strategy';\n\nconst createPayPalCommerceFastlanePaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceFastlanePaymentStrategy(\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\n]);\n","import { CardinalThreeDSecureFlow } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class PaypalProPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n protected paymentIntegrationService: PaymentIntegrationService,\n private threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this.threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n\n const state = this.paymentIntegrationService.getState();\n\n if (state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE) {\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: { methodId },\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n if (state.getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this.threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalProPaymentStrategy from './paypal-pro-payment-strategy';\n\nconst createPayPalProPaymentStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PaypalProPaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlow(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n\nexport default toResolvableModule(createPayPalProPaymentStrategy, [{ id: 'paypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class SagePayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private _formPoster: FormPoster,\n ) {\n super(paymentIntegrationService);\n }\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData } = payment;\n\n if (!paymentData) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n if (this._isThreeDSTwoExperimentOn()) {\n const newPaymentData = {\n ...paymentData,\n browser_info: getBrowserInfo(),\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error: Error) => {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n let payload;\n\n if (this._isThreeDSTwoExperimentOn() && !error.body.three_ds_result.merchant_data) {\n payload = {\n creq: error.body.three_ds_result.payer_auth_request,\n };\n } else {\n payload = {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n };\n }\n\n this._formPoster.postForm(\n error.body.three_ds_result.acs_url,\n payload,\n undefined,\n '_top',\n );\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return super.finalize();\n }\n\n private _isThreeDSTwoExperimentOn(): boolean {\n return (\n this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings\n .features['INT-4994.Opayo_3DS2'] === true\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SagePayPaymentStrategy from './sage-pay-payment-strategy';\n\nconst createSagePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new SagePayPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createSagePayPaymentStrategy, [{ id: 'sagepay' }]);\n","import { ExternalPaymentStrategy } from '@bigcommerce/checkout-sdk/external-integration';\n\nexport default class SezzlePaymentStrategy extends ExternalPaymentStrategy {\n protected redirectUrl(url: string): void {\n window.location.replace(url);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SezzlePaymentStrategy from './sezzle-payment-strategy';\n\nconst createSezzlePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new SezzlePaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createSezzlePaymentStrategy, [{ id: 'sezzle' }]);\n","export enum SquareIntent {\n CHARGE = 'CHARGE',\n STORE = 'STORE',\n}\n","import { fromEvent, merge, Subscription } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\n\nimport {\n BillingAddress,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentExecuteError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SquareIntent } from './enums';\nimport SquareV2PaymentInitializeOptions from './squarev2-payment-initialize-options';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\nimport {\n BillingContact,\n Card,\n CardInputEvent,\n CardInputEventTypes,\n ChargeVerifyBuyerDetails,\n Payments,\n SqEvent,\n StoreVerifyBuyerDetails,\n} from './types';\n\nexport interface SquareV2PaymentProcessorOptions {\n applicationId: string;\n locationId?: string;\n testMode?: boolean;\n}\n\nexport default class SquareV2PaymentProcessor {\n private _payments?: Payments;\n private _card?: Card;\n private _formValidationSubscription?: Subscription;\n\n constructor(\n private _scriptLoader: SquareV2ScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize({\n testMode,\n applicationId,\n locationId,\n }: SquareV2PaymentProcessorOptions): Promise {\n const square = await this._scriptLoader.load(testMode);\n\n this._payments = square.payments(applicationId, locationId);\n }\n\n async deinitialize(): Promise {\n if (this._formValidationSubscription) {\n this._formValidationSubscription.unsubscribe();\n }\n\n if (this._card) {\n await this._card.destroy();\n }\n\n this._formValidationSubscription = undefined;\n this._card = undefined;\n this._payments = undefined;\n }\n\n async initializeCard({\n containerId,\n style,\n onValidationChange,\n }: SquareV2PaymentInitializeOptions): Promise {\n const { postalCode } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n this._card = await this._getPayments().card();\n await this._card.attach(`#${containerId}`);\n\n try {\n await this._card.configure({ postalCode, style });\n } catch (_error) {\n /* Do nothing: we should not block shoppers from buying. */\n }\n\n if (onValidationChange) {\n this._formValidationSubscription = this._subscribeToFormValidation(\n this._card,\n onValidationChange,\n );\n }\n }\n\n async tokenize(): Promise {\n const result = await this._getCard().tokenize();\n\n if (result.status !== 'OK' || !result.token) {\n let errorMessage = `Tokenization failed with status: ${result.status}`;\n\n if (result.errors) {\n errorMessage += ` and errors: ${JSON.stringify(result.errors)}`;\n }\n\n throw new PaymentExecuteError(\n 'payment.errors.card_error',\n 'SquareV2TokenizationError',\n errorMessage,\n );\n }\n\n return result.token;\n }\n\n async verifyBuyer(token: string, intent: SquareIntent): Promise {\n return intent === SquareIntent.CHARGE\n ? this._chargeVerifyBuyer(token)\n : this._storeVerifyBuyer(token);\n }\n\n private _getPayments(): Payments {\n return guard(\n this._payments,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _subscribeToFormValidation(\n card: Card,\n observer: Required['onValidationChange'],\n ): Subscription {\n const blacklist = ['cardNumber', 'cvv'];\n const invalidFields = new Set(blacklist);\n const eventObservables = [\n 'focusClassAdded',\n 'focusClassRemoved',\n 'errorClassAdded',\n 'errorClassRemoved',\n 'cardBrandChanged',\n 'postalCodeChanged',\n ].map((eventType) => fromEvent(card, eventType as CardInputEventTypes));\n\n return merge(...eventObservables)\n .pipe(\n map((event: SqEvent): boolean => {\n const {\n detail: {\n field,\n currentState: { isCompletelyValid },\n },\n } = event;\n\n if (blacklist.includes(field)) {\n invalidFields[isCompletelyValid ? 'delete' : 'add'](field);\n }\n\n return invalidFields.size === 0;\n }),\n distinctUntilChanged(),\n )\n .subscribe(observer);\n }\n\n private _getCard(): Card {\n return guard(\n this._card,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _mapToSquareBillingContact({\n firstName: givenName,\n lastName: familyName,\n address1,\n address2,\n city,\n stateOrProvinceCode: state,\n postalCode,\n countryCode,\n email,\n phone,\n }: BillingAddress): BillingContact {\n return {\n givenName,\n familyName,\n addressLines: [address1, address2],\n city,\n state,\n postalCode,\n countryCode,\n email,\n phone,\n };\n }\n\n private async _chargeVerifyBuyer(token: string): Promise {\n const { getCheckoutOrThrow, getBillingAddressOrThrow } =\n this._paymentIntegrationService.getState();\n const { outstandingBalance, cart } = getCheckoutOrThrow();\n\n const details: ChargeVerifyBuyerDetails = {\n amount: outstandingBalance.toString(),\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n currencyCode: cart.currency.code,\n intent: SquareIntent.CHARGE,\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n\n private async _storeVerifyBuyer(token: string): Promise {\n const { getBillingAddressOrThrow } = this._paymentIntegrationService.getState();\n\n const details: StoreVerifyBuyerDetails = {\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n intent: SquareIntent.STORE,\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n}\n","import {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SquareIntent } from './enums';\nimport { WithSquareV2PaymentInitializeOptions } from './squarev2-payment-initialize-options';\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport {\n SquareCreditCardTokens,\n SquareFormattedVaultedInstrument,\n SquareInitializationData,\n SquarePaymentMethodInitializationData,\n} from './types';\n\nexport default class SquareV2PaymentStrategy implements PaymentStrategy {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _squareV2PaymentProcessor: SquareV2PaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithSquareV2PaymentInitializeOptions,\n ): Promise {\n if (!options?.squarev2?.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const { methodId, squarev2 } = options;\n const {\n config: { testMode },\n initializationData,\n } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n const { applicationId, locationId } = initializationData || {};\n\n if (!applicationId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this._squareV2PaymentProcessor.initialize({\n applicationId,\n locationId,\n testMode,\n });\n await this._squareV2PaymentProcessor.initializeCard(squarev2);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, paymentData } = payment;\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n await this._paymentIntegrationService.submitOrder();\n\n const submitPaymentPayload =\n paymentData && isVaultedInstrument(paymentData)\n ? await this._getVaultedInstrumentPayload(methodId, paymentData)\n : await this._getCardPayload(shouldSaveInstrument);\n\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n ...submitPaymentPayload,\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._squareV2PaymentProcessor.deinitialize();\n }\n\n private _shouldVerify(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return features['PROJECT-3828.add_3ds_support_on_squarev2'];\n }\n\n private async _getCardPayload(shouldSaveInstrument?: boolean) {\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (!this._shouldVerify()) {\n return {\n credit_card_token: {\n token: cardTokenizationResult,\n },\n };\n }\n\n let tokenData: SquareCreditCardTokens = {\n nonce: cardTokenizationResult,\n token: await this._squareV2PaymentProcessor.verifyBuyer(\n cardTokenizationResult,\n SquareIntent.CHARGE,\n ),\n };\n\n if (shouldSaveInstrument) {\n // INFO: additional 'tokenize' is required to verify and save the card\n // for each 'verifyBuyer' we need to generate new token\n const tokenForSavingCard = await this._squareV2PaymentProcessor.tokenize();\n\n tokenData = {\n ...tokenData,\n store_card_nonce: tokenForSavingCard,\n store_card_token: await this._squareV2PaymentProcessor.verifyBuyer(\n tokenForSavingCard,\n SquareIntent.STORE,\n ),\n };\n }\n\n return {\n credit_card_token: {\n token: JSON.stringify(tokenData),\n },\n };\n }\n\n private async _getVaultedInstrumentPayload(\n methodId: string,\n paymentData: VaultedInstrument,\n ): Promise {\n const { instrumentId } = paymentData;\n const verificationToken = this._shouldVerify()\n ? await this._squareV2PaymentProcessor.verifyBuyer(\n await this._getSquareCardIdOrThrow(methodId, instrumentId),\n SquareIntent.CHARGE,\n )\n : undefined;\n\n return {\n bigpay_token: {\n token: instrumentId,\n ...(verificationToken && { three_d_secure: { token: verificationToken } }),\n },\n };\n }\n\n private async _getSquareCardIdOrThrow(methodId: string, instrumentId: string): Promise {\n const state = await this._paymentIntegrationService.loadPaymentMethod(methodId, {\n params: { method: methodId, bigpayToken: instrumentId },\n });\n\n const { initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { cardId } = initializationData || {};\n\n if (!cardId) {\n throw new PaymentArgumentInvalidError(['cardId']);\n }\n\n return cardId;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport assertSquareV2Window from './is-squarev2-window';\nimport { Square } from './types';\n\nexport enum SquareV2WebPaymentsSdkEnv {\n LIVE = 'https://web.squarecdn.com/v1/square.js',\n SANDBOX = 'https://sandbox.web.squarecdn.com/v1/square.js',\n}\n\nexport default class SquareV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? SquareV2WebPaymentsSdkEnv.SANDBOX : SquareV2WebPaymentsSdkEnv.LIVE,\n );\n\n assertSquareV2Window(window);\n\n return window.Square;\n }\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport type { Square } from './types';\n\ninterface SquareV2HostWindow extends Window {\n Square: Square;\n}\n\nfunction isSquareV2Window(window: Window): window is SquareV2HostWindow {\n return 'Square' in window;\n}\n\nexport default function assertSquareV2Window(window: Window): asserts window is SquareV2HostWindow {\n if (!isSquareV2Window(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport SquareV2PaymentStrategy from './squarev2-payment-strategy';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\n\nconst createSquareV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new SquareV2PaymentStrategy(\n paymentIntegrationService,\n new SquareV2PaymentProcessor(\n new SquareV2ScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n ),\n );\n};\n\nexport default toResolvableModule(createSquareV2PaymentStrategy, [{ id: 'squarev2' }]);\n","import { IndividualCardElementOptions } from './stripev3';\n\nexport default function isIndividualCardElementOptions(\n individualCardElementOptions: any,\n): individualCardElementOptions is IndividualCardElementOptions {\n return (\n individualCardElementOptions !== null &&\n typeof individualCardElementOptions === 'object' &&\n 'cardNumberElementOptions' in individualCardElementOptions &&\n 'cardCvcElementOptions' in individualCardElementOptions &&\n 'cardExpiryElementOptions' in individualCardElementOptions &&\n typeof individualCardElementOptions.cardNumberElementOptions !== 'undefined' &&\n typeof individualCardElementOptions.cardCvcElementOptions !== 'undefined' &&\n typeof individualCardElementOptions.cardExpiryElementOptions !== 'undefined'\n );\n}\n","interface BaseElementOptions {\n /**\n * Customize the appearance of an element using CSS properties passed in a [Style](https://stripe.com/docs/js/appendix/style) object,\n * which consists of CSS properties nested under objects for each variant.\n */\n style?: StripeElementStyle;\n\n /**\n * Set custom class names on the container DOM element when the Stripe element is in a particular state.\n */\n classes?: StripeElementClasses;\n\n /**\n * Applies a disabled state to the Element such that user input is not accepted. Default is false.\n */\n disabled?: boolean;\n}\n\nexport interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {\n card?: StripeElement;\n}\n\nexport interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {\n ideal?: StripeElement;\n}\n\nexport interface CreatePaymentMethodSepaData extends PaymentMethodCreateParams {\n sepa_debit?: StripeElement;\n}\n\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * Status of this PaymentIntent. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses).\n */\n status: 'succeeded' | string;\n\n /**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\n last_payment_error: LastPaymentError | null;\n}\n\n/**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\nexport interface LastPaymentError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n}\n\n/**\n * The PaymentMethod object\n */\nexport interface PaymentMethod {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value.\n * It contains additional information specific to the PaymentMethod type.\n */\n type: string;\n}\n\nexport interface PaymentMethodCreateParams {\n /**\n * Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.\n */\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n\n /**\n * A human-readable code for the error obtained\n */\n code?: string;\n}\n\n/**\n * CSS properties supported by Stripe.js.\n */\ninterface StripeElementCSSProperties {\n /**\n * The [background-color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) CSS property.\n *\n * This property works best with the `::selection` pseudo-class.\n * In other cases, consider setting the background color on the element's container instaed.\n */\n backgroundColor?: string;\n\n /**\n * The [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS property.\n */\n color?: string;\n\n /**\n * The [font-family](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) CSS property.\n */\n fontFamily?: string;\n\n /**\n * The [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) CSS property.\n */\n fontSize?: string;\n\n /**\n * The [font-smoothing](https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing) CSS property.\n */\n fontSmoothing?: string;\n\n /**\n * The [font-style](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) CSS property.\n */\n fontStyle?: string;\n\n /**\n * The [font-variant](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) CSS property.\n */\n fontVariant?: string;\n\n /**\n * The [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) CSS property.\n */\n fontWeight?: string;\n\n /**\n * A custom property, used to set the color of the icons that are rendered in an element.\n */\n iconColor?: string;\n\n /**\n * The [line-height](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property.\n *\n * To avoid cursors being rendered inconsistently across browsers, consider using a padding on the element's container instead.\n */\n lineHeight?: string;\n\n /**\n * The [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) CSS property.\n */\n letterSpacing?: string;\n\n /**\n * The [text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) CSS property.\n *\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n textAlign?: string;\n\n /**\n * The [padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) CSS property.\n *\n * Available for the `idealBank` element.\n * Accepts integer `px` values.\n */\n padding?: string;\n\n /**\n * The [text-decoration](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) CSS property.\n */\n textDecoration?: string;\n\n /**\n * The [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) CSS property.\n */\n textShadow?: string;\n\n /**\n * The [text-transform](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) CSS property.\n */\n textTransform?: string;\n}\n\ninterface StripeElementStyleVariant extends StripeElementCSSProperties {\n ':hover'?: StripeElementCSSProperties;\n\n ':focus'?: StripeElementCSSProperties;\n\n '::placeholder'?: StripeElementCSSProperties;\n\n '::selection'?: StripeElementCSSProperties;\n\n ':-webkit-autofill'?: StripeElementCSSProperties;\n\n /**\n * Available for all elements except the `paymentRequestButton` element\n */\n ':disabled'?: StripeElementCSSProperties;\n\n /**\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n '::-ms-clear'?: StripeElementCSSProperties & { display: string };\n}\n\nexport interface CardElementOptions extends BaseElementOptions {\n /**\n * A pre-filled set of values to include in the input (e.g., {postalCode: '94110'}).\n * Note that sensitive card information (card number, CVC, and expiration date)\n * cannot be pre-filled\n */\n value?: string;\n\n /**\n * Hide the postal code field. Default is false. If you are already collecting a\n * full billing address or postal code elsewhere, set this to true.\n */\n hidePostalCode?: boolean;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n\n /*\n * Hides the icon in the Element, Default is false\n */\n hideIcon?: boolean;\n}\n\ninterface BaseIndividualElementOptions extends BaseElementOptions {\n containerId: string;\n}\n\nexport interface CardNumberElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n\n showIcon?: boolean;\n /**\n * Appearance of the icon in the Element. Either `solid` or `default`\n */\n iconStyle?: IconStyle;\n}\n\nexport interface CardExpiryElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface CardCvcElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface IbanElementOptions extends BaseElementOptions {\n /**\n * Specify the list of countries or country-groups whose IBANs you want to allow.\n * Must be ['SEPA'].\n */\n supportedCountries?: string[];\n\n /**\n * Customize the country and format of the placeholder IBAN. Default is DE.\n */\n placeholderCountry?: string;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n}\n\nexport interface IdealElementOptions extends BaseElementOptions {\n value?: string;\n\n /**\n * Hides the icon in the Element. Default is false.\n */\n hideIcon?: boolean;\n}\n\nexport interface ZipCodeElementOptions {\n containerId: string;\n}\n\nexport enum IconStyle {\n Solid = 'solid',\n Default = 'default',\n}\n\nexport interface StripeElementStyle {\n /**\n * Base variant—all other variants inherit from these styles.\n */\n base?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has valid input.\n */\n complete?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has no customer input.\n */\n empty?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has invalid input.\n */\n invalid?: StripeElementStyleVariant;\n}\n\nexport interface StripeElementClasses {\n /**\n * The base class applied to the container. Defaults to StripeElement.\n */\n base?: string;\n\n /**\n * The class name to apply when the Element is complete. Defaults to StripeElement--complete.\n */\n complete?: string;\n\n /**\n * The class name to apply when the Element is empty. Defaults to StripeElement--empty.\n */\n empty?: string;\n\n /**\n * The class name to apply when the Element is focused. Defaults to StripeElement--focus.\n */\n focus?: string;\n\n /**\n * The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.\n */\n invalid?: string;\n\n /**\n * The class name to apply when the Element has its value autofilled by the browser\n * (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.\n */\n webkitAutoFill?: string;\n}\n\nexport interface StripeAddress {\n /**\n * City, district, suburb, town, or village.\n */\n city?: string;\n\n /**\n * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).\n */\n country?: string;\n\n /**\n * Address line 1 (e.g., street, PO Box, or company name).\n */\n line1: string;\n\n /**\n * Address line 2 (e.g., apartment, suite, unit, or building).\n */\n line2?: string;\n\n /**\n * ZIP or postal code.\n */\n postal_code?: string;\n\n /**\n * State, county, province, or region.\n */\n state?: string;\n}\n\nexport interface StripeBillingDetails {\n /**\n * Billing address.\n */\n address?: StripeAddress;\n\n /**\n * Email address.\n */\n email?: string;\n\n /**\n * Full name.\n */\n name?: string;\n\n /**\n * Billing phone number (including extension).\n */\n phone?: string;\n}\n\nexport interface StripeShippingAddress {\n /**\n * Shipping Address\n */\n address: StripeAddress;\n\n /**\n * Recipient name\n */\n name: string;\n\n /**\n * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.\n */\n carrier?: string;\n\n /**\n * Recipient phone (including extension).\n */\n phone?: string;\n\n /**\n * The tracking number for a physical product, obtained from the delivery service.\n * If multiple tracking numbers were generated for this purchase, please separate them with commas.\n */\n tracking_number?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmAlipayPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmAlipayPaymentData {\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmCardPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmCardPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodCardData;\n\n /*\n * The [shipping details](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping) for the payment, if collected.\n *\n * @recommended\n */\n shipping?: StripeShippingAddress;\n\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n\n /**\n * Indicates that you intend to make future payments with this PaymentIntent's payment method.\n *\n * If present, the payment method used with this PaymentIntent can be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer, even after the transaction completes.\n *\n * Use `on_session` if you intend to only reuse the payment method when your customer is present in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow.\n */\n setup_future_usage?: 'off_session' | 'on_session' | null;\n}\n\n/**\n * Data to be sent with a `stripe.confirmIdealPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmIdealPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodIdealData;\n\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmSEPAPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmSepaPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodSepaData;\n}\n\nexport type StripeConfirmPaymentData =\n | StripeConfirmAlipayPaymentData\n | StripeConfirmCardPaymentData\n | StripeConfirmIdealPaymentData\n | StripeConfirmSepaPaymentData\n | undefined;\n\nexport type StripeElementOptions =\n | CardElementOptions\n | CardExpiryElementOptions\n | CardNumberElementOptions\n | CardCvcElementOptions\n | IdealElementOptions\n | IbanElementOptions\n | ZipCodeElementOptions;\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n}\n\nexport interface StripeElements {\n /**\n * Creates a `AlipayElement` | `CardElement` | `CardCvcElement` |`CardExpiryElement` | `CardExpiryElement` | `CardNumberElement` | `IdealBankElement` | `IbanElement`.\n */\n create(elementType: StripeElementType, options?: StripeElementOptions): StripeElement;\n\n /**\n * Looks up a previously created `Element` by its type.\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CssFontSource {\n /**\n * A relative or absolute URL pointing to a CSS file with [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definitions, for example:\n * `https://fonts.googleapis.com/css?family=Open+Sans`\n * Note that if you are using a [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),\n * [additional directives](https://stripe.com/docs/security#content-security-policy) may be necessary.\n */\n cssSrc: string;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CustomFontSource {\n /**\n * The name to give the font.\n */\n family: string;\n\n /**\n * A valid [src](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src) value pointing to your\n * custom font file. This is usually (though not always) a link to a file with a .woff , .otf, or .svg suffix.\n */\n src: string;\n\n /**\n * A valid [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) value.\n */\n display?: string;\n\n /**\n * One of normal, italic, oblique. Defaults to normal.\n */\n style?: string;\n\n /**\n * A valid [unicode-range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) value.\n */\n unicodeRange?: string;\n\n /**\n * A valid [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight). Note that this is a string, not a number.\n */\n weight?: string;\n}\n\nexport type CustomFont = CssFontSource | CustomFontSource;\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n}\n\nexport interface StripeConfirmPaymentOptions {\n /**\n * Set this to false if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect). Default is true.\n */\n handleActions?: boolean;\n}\n\nexport interface StripeV3Client {\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options?: StripeElementsOptions): StripeElements;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment\n *\n * Use `stripe.confirmAlipayPayment` in the Alipay payment method creation flow when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with data you provide, and it will automatically\n * redirect the customer to the authorize the transaction. Once authorization is complete, the customer will be redirected\n * back to your specified `return_url`. When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmAlipayPayment` by default, will trigger a redirect when successful. If there is an error, or when handling\n * `next_actions` manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result` object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmAlipayPayment` may take several seconds to complete. During that time, you should disable your\n * form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result, you should\n * be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmAlipayPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmAlipayPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment\n *\n * Use `stripe.confirmCardPayment` when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents)\n * with `data` you provide and carry out 3DS or other next actions if they are required.\n *\n * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will\n * trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmCardPayment` will return a Promise which resolves with a result object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that stripe.confirmCardPayment may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n *\n * Additionally, `stripe.confirmCardPayment may trigger` a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication\n * challenge. This will be shown in a modal dialog and may be confusing for customers using assistive technologies like\n * screen readers. You should make your form accessible by ensuring that success or error messages are clearly read out\n * after this method completes.\n *\n */\n confirmCardPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmCardPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment\n *\n * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal)\n * flow when the customer submits your payment form. When called, it will confirm the `PaymentIntent` with `data` you\n * provide, and it will automatically redirect the customer to the authorize the transaction.\n * Once authorization is complete, the customer will be redirected back to your specified `return_url`.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * By default, `stripe.confirmIdealPayment` will trigger a redirect when successful. If there is an error, or when handling\n * next actions manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result`\n * object. This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmIdealPayment` may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmIdealPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmIdealPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n *\n * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit)\n * with Payment Methods flow when the customer submits your payment form. When called, it will confirm the\n * [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. Note that there are some additional\n * requirements to this flow that are not covered in this reference. Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit\n * for more details.\n *\n * When you confirm a PaymentIntent, it needs to have an attached PaymentMethod. In addition to confirming the PaymentIntent,\n * this method can automatically create and attach a new PaymentMethod for you. If you have already attached a\n * [PaymentMethod](https://stripe.com/docs/api/payment_methods) you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment\n */\n confirmSepaDebitPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\n data?: StripeConfirmSepaPaymentData,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * Use stripe.createPaymentMethod to convert payment information collected by elements into a PaymentMethod\n * object that you safely pass to your server to use in an API call.\n *\n * @docs https://stripe.com/docs/js/payment_methods/create_payment_method\n *\n * @param type: String, The type of the PaymentMethod to create. Refer to the PaymentMethod API for all possible values.\n * @param card: StripeElement, A card or cardNumber Element.\n * @param billing_details: StripeBillingDetails, Billing information associated with the PaymentMethod that\n * may be used or required by particular types of payment methods.\n */\n createPaymentMethod(\n params: CreatePaymentMethodParams,\n ): Promise<{ paymentMethod?: PaymentMethod; error?: StripeError }>;\n\n /*\n * Use stripe.handleCardAction in the Payment Intents API manual confirmation flow to handle a PaymentIntent\n * with the requires_action status. It will throw an error if the PaymentIntent has a different status.\n *\n * @docs https://stripe.com/docs/js/payment_intents/handle_card_action\n *\n * @param paymentIntentClientSecret: String, The client secret of the PaymentIntent to handle.\n */\n handleCardAction(\n paymentIntentClientSecret: string,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n}\n\nexport interface CreatePaymentMethodParams {\n type: StripePaymentMethodType;\n card: StripeElement;\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeHostWindow extends Window {\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeV3Client;\n}\n\nexport enum StripeElementType {\n Alipay = 'alipay',\n CardCvc = 'cardCvc',\n CardExpiry = 'cardExpiry',\n CardNumber = 'cardNumber',\n CreditCard = 'card',\n IDEAL = 'idealBank',\n Sepa = 'iban',\n}\n\nexport enum StripePaymentMethodType {\n Alipay = 'alipay',\n CreditCard = 'card',\n IDEAL = 'ideal',\n Sepa = 'sepa_debit',\n}\n\n/**\n * Initialization options.\n */\nexport interface StripeConfigurationOptions {\n /**\n * For usage with [Connect](https://stripe.com/docs/connect) only.\n * Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account.\n */\n stripeAccount: string;\n\n /**\n * Override your account's [API version](https://stripe.com/docs/api/versioning)\n */\n apiVersion?: string;\n\n /**\n * A locale used to globally configure localization in Stripe. Setting the locale here will localize error strings for all Stripe.js methods. It will also configure the locale for Elements and Checkout. Default is auto (Stripe detects the locale of the browser).\n * Note that Checkout supports a slightly different set of locales than Stripe.js.\n */\n locale?: string;\n\n betas?: string[];\n}\n\nexport interface StripeAdditionalActionData {\n redirect_url?: string;\n intent?: string;\n}\n\nexport interface StripeAdditionalAction {\n type: string;\n data: StripeAdditionalActionData;\n}\n\nexport interface StripeCardElements {\n [index: number]: StripeElement;\n}\n\nexport interface IndividualCardElementOptions {\n cardCvcElementOptions: CardCvcElementOptions;\n cardExpiryElementOptions: CardExpiryElementOptions;\n cardNumberElementOptions: CardNumberElementOptions;\n zipCodeElementOptions?: ZipCodeElementOptions;\n}\n\nexport interface StripeV3PaymentMethod extends PaymentMethod {\n initializationData: StripeV3InitializationData;\n}\n\nexport interface StripeV3InitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n useIndividualCardFields: boolean;\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport enum StripeV3ErrorType {\n AuthFailure = 'auth_failure',\n}\n\nexport default class StripeV3Error extends StandardError {\n subtype: string;\n\n constructor(subtype: StripeV3ErrorType) {\n super(getErrorMessage(subtype));\n\n this.type = 'stripev3_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: StripeV3ErrorType) {\n switch (type) {\n case StripeV3ErrorType.AuthFailure:\n return `User did not authenticate`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { includes, isEmpty, omitBy, some } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n Customer,\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isBillingAddressLike,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StripeV3FormattedPayload,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isIndividualCardElementOptions from './is-individual-card-element-options';\nimport {\n PaymentIntent,\n StripeAdditionalAction,\n StripeAddress,\n StripeBillingDetails,\n StripeCardElements,\n StripeConfirmIdealPaymentData,\n StripeConfirmPaymentData,\n StripeConfirmSepaPaymentData,\n StripeElement,\n StripeElementOptions,\n StripeElements,\n StripeElementType,\n StripeError,\n PaymentMethod as StripePaymentMethod,\n StripePaymentMethodType,\n StripeV3Client,\n StripeV3PaymentMethod,\n} from './stripev3';\nimport StripeV3Error, { StripeV3ErrorType } from './stripev3-error';\nimport StripeV3PaymentInitializeOptions, {\n WithStripeV3PaymentInitializeOptions,\n} from './stripev3-initialize-options';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst APM_REDIRECT = [StripeElementType.Alipay, StripeElementType.IDEAL];\n\nexport default class StripeV3PaymentStrategy implements PaymentStrategy {\n private initializeOptions?: StripeV3PaymentInitializeOptions;\n private stripeV3Client?: StripeV3Client;\n private stripeElements?: StripeElements;\n private stripeElement?: StripeElement;\n private stripeCardElements?: StripeCardElements;\n private useIndividualCardFields?: boolean;\n private hostedForm?: HostedForm;\n private isDeinitialize?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeV3ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions & WithStripeV3PaymentInitializeOptions) {\n const { stripev3, methodId, gatewayId } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this.initializeOptions = stripev3;\n this.isDeinitialize = false;\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n const {\n initializationData: {\n stripePublishableKey,\n stripeConnectedAccount,\n useIndividualCardFields,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n const form = this.getInitializeOptions().form;\n\n this.useIndividualCardFields = useIndividualCardFields;\n this.stripeV3Client = await this.loadStripeJs(stripePublishableKey, stripeConnectedAccount);\n\n if (\n this.isCreditCard(methodId) &&\n this.shouldShowTSVHostedForm(methodId, gatewayId) &&\n form\n ) {\n this.hostedForm = await this.mountCardVerificationFields(form);\n } else {\n this.stripeElement = await this.mountCardFields(methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n let formattedPayload: StripeV3FormattedPayload;\n let stripeError: StripeError | undefined;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, gatewayId, methodId } = payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const shouldSubmitOrderBeforeLoadingAPM = includes(APM_REDIRECT, methodId);\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n try {\n if (shouldSubmitOrderBeforeLoadingAPM) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n if (gatewayId) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n const state = this.paymentIntegrationService.getState();\n\n if (isVaultedInstrument(paymentData)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { instrumentId } = paymentData;\n const paymentMethod = state.getPaymentMethodOrThrow(payment.methodId);\n const clientToken = paymentMethod.clientToken;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return await this.executeWithVaulted(\n payment,\n instrumentId,\n shouldSetAsDefaultInstrument,\n clientToken,\n );\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const result = await this.confirmStripePayment(paymentMethod);\n const { clientToken, method } = paymentMethod;\n const { id: token } = result.paymentIntent ?? result.paymentMethod ?? { id: '' };\n\n stripeError = result.error;\n\n formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (method === StripeElementType.CreditCard) {\n formattedPayload.client_token = clientToken;\n }\n\n if (!shouldSubmitOrderBeforeLoadingAPM) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n const paymentPayload = this.buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this.processAdditionalAction(\n this.handleEmptyPaymentIntentError(error, stripeError),\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n this.isDeinitialize = true;\n this.unmountElement();\n\n return Promise.resolve();\n }\n\n private buildPaymentPayload(\n methodId: string,\n formattedPayload: StripeV3FormattedPayload,\n shouldSetAsDefaultInstrument: boolean | undefined,\n ): Payment {\n const paymentData = shouldSetAsDefaultInstrument\n ? {\n formattedPayload: {\n ...formattedPayload,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n }\n : { formattedPayload };\n\n return { methodId, paymentData };\n }\n\n private isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private isAuthError(stripeError: StripeError | undefined) {\n return stripeError?.code === 'payment_intent_authentication_failure';\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === StripePaymentMethodType.CreditCard;\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private async confirmStripePayment(paymentMethod: PaymentMethod): Promise<{\n paymentIntent?: PaymentIntent | undefined;\n paymentMethod?: StripePaymentMethod | undefined;\n error?: StripeError | undefined;\n }> {\n const { clientToken: clientSecret, method, returnUrl } = paymentMethod;\n\n if (!clientSecret) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n switch (method) {\n case StripeElementType.Alipay:\n return this.getStripeJs().confirmAlipayPayment(\n clientSecret,\n { return_url: returnUrl },\n { handleActions: false },\n );\n\n case StripeElementType.IDEAL: {\n const data = this.mapStripePaymentData(StripePaymentMethodType.IDEAL, returnUrl);\n\n return this.getStripeJs().confirmIdealPayment(clientSecret, data, {\n handleActions: false,\n });\n }\n\n case StripeElementType.Sepa: {\n const data = this.mapStripePaymentData(StripePaymentMethodType.Sepa);\n\n return this.getStripeJs().confirmSepaDebitPayment(clientSecret, data);\n }\n\n default: {\n const card = this.useIndividualCardFields\n ? this.getStripeCardElements()[0]\n : this.getStripeElement();\n const billingDetails = this.mapStripeBillingDetails(\n this.paymentIntegrationService.getState().getBillingAddress(),\n this.paymentIntegrationService.getState().getCustomer(),\n );\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n });\n }\n }\n }\n\n private async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n token: string,\n shouldSetAsDefaultInstrument: boolean | undefined,\n clientToken: string,\n ): Promise {\n const formattedPayload = {\n bigpay_token: { token },\n confirm: true,\n client_token: clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (\n this.isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId) &&\n this.hostedForm\n ) {\n const form = this.hostedForm;\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n payment.paymentData = {\n ...payment.paymentData,\n instrumentId: JSON.stringify({\n token: payment.paymentData?.instrumentId || '',\n client_token: clientToken,\n }),\n };\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this.paymentIntegrationService.loadCurrentOrder();\n }\n\n const paymentPayload = this.buildPaymentPayload(\n payment.methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private getInitializeOptions(): StripeV3PaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private getStripeCardElements(): StripeCardElements {\n if (!this.stripeCardElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeCardElements;\n }\n\n private getStripeElement(): StripeElement {\n if (!this.stripeElement) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeElement;\n }\n\n private getStripeJs(): StripeV3Client {\n if (!this.stripeV3Client) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeV3Client;\n }\n\n private handleEmptyPaymentIntentError(error: unknown, stripeError: StripeError | undefined) {\n if (!isRequestError(error)) {\n return error;\n }\n\n return some(error.body.errors, { code: 'required_field' }) && stripeError\n ? new Error(stripeError.message)\n : error;\n }\n\n private async loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeV3Client) {\n return Promise.resolve(this.stripeV3Client);\n }\n\n return this.scriptLoader.load(\n stripePublishableKey,\n stripeConnectedAccount,\n this.paymentIntegrationService.getState().getLocale(),\n );\n }\n\n private mapStripeAddress(address?: Address): StripeAddress {\n if (address) {\n const {\n city,\n countryCode: country,\n address1: line1,\n address2: line2,\n postalCode,\n stateOrProvinceCode: state,\n } = address;\n\n return { city, country, line1, line2, postal_code: postalCode, state };\n }\n\n return { line1: '' };\n }\n\n private mapStripeBillingDetails(\n billingAddress?: BillingAddress,\n customer?: Customer,\n ): StripeBillingDetails {\n const { firstName, lastName } = billingAddress ||\n customer || { firstName: 'Guest', lastName: '' };\n const name = `${firstName} ${lastName}`.trim();\n const { options } = this.getInitializeOptions();\n\n if (this.useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const { zipCodeElementOptions } = options;\n\n if (zipCodeElementOptions) {\n const postalCode = document.getElementById(zipCodeElementOptions.containerId)\n ? (\n document.getElementById(\n zipCodeElementOptions.containerId,\n ) as HTMLInputElement\n ).value\n : '';\n\n if (postalCode && billingAddress) {\n billingAddress = { ...billingAddress, postalCode };\n }\n }\n }\n\n const address = {\n address: this.mapStripeAddress(billingAddress),\n };\n\n if (customer && customer.addresses[0] && isBillingAddressLike(customer.addresses[0])) {\n const customerAddress = customer.addresses[0];\n const { email } = customer;\n const { phone } = customerAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n if (billingAddress) {\n const { email, phone } = billingAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n return { ...address, name };\n }\n\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.IDEAL,\n returnUrl?: string,\n ): StripeConfirmIdealPaymentData;\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.Sepa,\n ): StripeConfirmSepaPaymentData;\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const customer = this.paymentIntegrationService.getState().getCustomer();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n const result: Partial = {\n payment_method: {\n [stripePaymentMethodType]: this.getStripeElement(),\n billing_details: this.mapStripeBillingDetails(billingAddress, customer),\n },\n };\n\n if (stripePaymentMethodType === StripePaymentMethodType.IDEAL) {\n return { ...result, return_url: returnUrl };\n }\n\n return result;\n }\n\n private mountCardFields(methodId: string): Promise {\n const { options, containerId } = this.getInitializeOptions();\n\n let stripeElement: StripeElement;\n\n return new Promise((resolve, reject) => {\n if (!this.stripeElements) {\n this.stripeElements = this.getStripeJs().elements();\n }\n\n switch (methodId) {\n case StripeElementType.CreditCard:\n if (this.useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const {\n cardNumberElementOptions,\n cardExpiryElementOptions,\n cardCvcElementOptions,\n } = options;\n\n const cardNumberElement =\n this.stripeElements.getElement(StripeElementType.CardNumber) ||\n this.stripeElements.create(\n StripeElementType.CardNumber,\n cardNumberElementOptions,\n );\n const cardExpiryElement =\n this.stripeElements.getElement(StripeElementType.CardExpiry) ||\n this.stripeElements.create(\n StripeElementType.CardExpiry,\n cardExpiryElementOptions,\n );\n const cardCvcElement =\n this.stripeElements.getElement(StripeElementType.CardCvc) ||\n this.stripeElements.create(\n StripeElementType.CardCvc,\n cardCvcElementOptions,\n );\n\n this.stripeCardElements = [\n cardNumberElement,\n cardExpiryElement,\n cardCvcElement,\n ];\n stripeElement = this.stripeCardElements[0];\n\n try {\n cardNumberElement.mount(`#${cardNumberElementOptions.containerId}`);\n cardExpiryElement.mount(`#${cardExpiryElementOptions.containerId}`);\n cardCvcElement.mount(`#${cardCvcElementOptions.containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n } else {\n stripeElement =\n this.stripeElements.getElement(methodId) ||\n this.stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n }\n\n break;\n\n case StripeElementType.IDEAL:\n case StripeElementType.Sepa:\n stripeElement =\n this.stripeElements.getElement(methodId) ||\n this.stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n\n break;\n\n case StripeElementType.Alipay:\n break;\n }\n\n resolve(stripeElement);\n });\n }\n\n private async mountCardVerificationFields(formOptions: HostedFormOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const bigpayBaseUrl = storeConfig.paymentSettings.bigpayBaseUrl;\n\n const form = this.paymentIntegrationService.createHostedForm(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private async processAdditionalAction(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!isRequestError(error)) {\n throw error;\n }\n\n const isAdditionalActionError = some(error.body.errors, {\n code: 'additional_action_required',\n });\n const isThreeDSecureRequiredError = some(error.body.errors, {\n code: 'three_d_secure_required',\n });\n\n if (isAdditionalActionError) {\n const action: StripeAdditionalAction = error.body.additional_action_required;\n\n if (action && action.type === 'redirect_to_url') {\n return new Promise(() => {\n if (action.data.redirect_url) {\n window.location.replace(action.data.redirect_url);\n }\n });\n }\n }\n\n if (isThreeDSecureRequiredError) {\n const clientSecret = error.body.three_ds_result.token;\n const needsConfirm = false;\n let catchedConfirmError = false;\n let result;\n\n try {\n result = await this.getStripeJs().confirmCardPayment(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n\n if (result?.error) {\n if (this.isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n if (this.isAuthError(result.error)) {\n throw new StripeV3Error(StripeV3ErrorType.AuthFailure);\n }\n\n throw new Error(result.error.message);\n }\n\n const token = this.getPaymentToken(\n result?.paymentIntent,\n clientSecret,\n catchedConfirmError,\n );\n\n const formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: needsConfirm,\n };\n\n const paymentPayload = this.buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n throw this.handleEmptyPaymentIntentError(error, result?.error);\n }\n }\n\n throw error;\n }\n\n private getPaymentToken(\n paymentIntent: PaymentIntent | undefined,\n clientSecret: string,\n catchedConfirmError: boolean,\n ): string {\n if (!paymentIntent || catchedConfirmError) {\n return clientSecret;\n }\n\n return paymentIntent.id;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this.isHostedFieldAvailable() && this.isHostedPaymentFormEnabled(methodId, gatewayId)\n );\n }\n\n private unmountElement(): void {\n if (this.stripeElement) {\n this.stripeElement.unmount();\n this.stripeElement = undefined;\n }\n }\n}\n","import BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: any): address is BillingAddress {\n return (\n typeof address === 'object' &&\n address !== null &&\n 'id' in address &&\n typeof address.id !== 'undefined'\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripeHostWindow, StripeV3Client } from './stripev3';\n\nexport default class StripeV3ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n load(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n return this.scriptLoader.loadScript('https://js.stripe.com/v3/').then(() => {\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.stripeWindow.Stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: ['payment_intent_beta_3', 'alipay_pm_beta_1'],\n apiVersion: '2020-03-02;alipay_beta=v1',\n });\n });\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeV3PaymentStrategy from './stripev3-payment-strategy';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst createStripeV3PaymentStrategy: PaymentStrategyFactory = (paymentIntegrationService) => {\n return new StripeV3PaymentStrategy(\n paymentIntegrationService,\n new StripeV3ScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeV3PaymentStrategy, [{ gateway: 'stripev3' }]);\n","import { includes, some } from 'lodash';\n\nimport {\n Address,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isStripeError } from './is-stripe-error';\nimport {\n AddressOptions,\n StripeAdditionalActionRequired,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeStringConstants,\n StripeUPEClient,\n StripeUPEPaymentIntentStatus,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions from './stripe-upe-initialize-options';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nexport default class StripeUPEIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeupe: StripeUPEPaymentInitializeOptions,\n stripeElements?: StripeElements,\n ): void {\n this.checkoutEventsUnsubscribe = this.paymentIntegrationService.subscribe(\n async () => {\n const paymentElement = stripeElements?.getElement(StripeElementType.PAYMENT);\n\n if (!paymentElement) {\n return;\n }\n\n try {\n await this.updateStripePaymentIntent(gatewayId, methodId);\n } catch (error) {\n if (this.isMounted) {\n paymentElement.unmount();\n this.isMounted = false;\n }\n\n if (error instanceof Error) {\n stripeupe.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeupe.containerId);\n }\n },\n (state) => state.getCheckout()?.outstandingBalance,\n (state) => state.getCheckout()?.coupons,\n );\n }\n\n mountElement(stripeElement: StripeElement, containerId: string): void {\n if (!document.getElementById(containerId)) {\n return;\n }\n\n stripeElement.mount(`#${containerId}`);\n this.isMounted = true;\n }\n\n mapAppearanceVariables(styles: NonNullable) {\n return {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n colorIcon: styles.fieldPlaceholderText,\n };\n }\n\n mapInputAppearanceRules(styles: NonNullable) {\n return {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n };\n }\n\n throwStripeError(stripeError?: unknown): never {\n if (isStripeError(stripeError)) {\n this.throwDisplayableStripeError(stripeError);\n\n if (this.isCancellationError(stripeError)) {\n throw new PaymentMethodCancelledError();\n }\n }\n\n throw new PaymentMethodFailedError();\n }\n\n throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n\n isCancellationError(stripeError?: StripeError): boolean {\n const errorMessage = stripeError?.payment_intent.last_payment_error?.message;\n\n return !!errorMessage && errorMessage.indexOf('canceled') !== -1;\n }\n\n throwPaymentConfirmationProceedMessage() {\n // INFO: for case if payment was successfully confirmed on Stripe side but on BC side something go wrong, request failed and order status hasn't changed yet\n // For shopper we need to show additional message that BC is waiting for stripe confirmation, to prevent additional payment creation\n throw new PaymentMethodFailedError(\n \"We've received your order and are processing your payment. Once the payment is verified, your order will be completed. We will send you an email when it's completed. Please note, this process may take a few minutes depending on the processing times of your chosen method.\",\n );\n }\n\n async isPaymentCompleted(\n methodId: string,\n stripeUPEClient?: StripeUPEClient,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n\n if (\n !paymentMethod.clientToken ||\n !stripeUPEClient ||\n !features['PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE']\n ) {\n return false;\n }\n\n const { paymentIntent } = await stripeUPEClient.retrievePaymentIntent(\n paymentMethod.clientToken,\n );\n\n return paymentIntent?.status === StripeUPEPaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { firstName, lastName, email } = billingAddress || {};\n const address = this._mapStripeAddress(billingAddress);\n\n if (!stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!email || !address || !address.city || !address.country || !firstName || !lastName) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n elements: stripeElements,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n payment_method_data: {\n billing_details: {\n email,\n address,\n name: `${firstName} ${lastName}`,\n },\n },\n ...(returnUrl && { return_url: returnUrl }),\n },\n };\n }\n\n isAdditionalActionError(errors: Array<{ code: string }>): boolean {\n return some(errors, { code: 'additional_action_required' });\n }\n\n isRedirectAction(additionalAction: StripeAdditionalActionRequired): boolean {\n const {\n type,\n data: { redirect_url },\n } = additionalAction;\n\n return type === 'redirect_to_url' && !!redirect_url;\n }\n\n isOnPageAdditionalAction(additionalAction: StripeAdditionalActionRequired): boolean {\n const {\n type,\n data: { token },\n } = additionalAction;\n\n return type === 'additional_action_requires_payment_method' && !!token;\n }\n\n async updateStripePaymentIntent(gatewayId: string, methodId: string): Promise {\n // INFO: to trigger payment intent update on the BE side we need to make stripe config request\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n private _mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const { city, address1, address2, countryCode: country, postalCode } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n}\n","import { StripeError } from './stripe-upe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n ar: ['ar'],\n bg: ['bg'],\n cs: ['cs'],\n da: ['da'],\n de: ['de'],\n el: ['el'],\n en: ['en', 'en-GB'],\n es: ['es', 'es-419'],\n et: ['et'],\n fi: ['fi'],\n fil: ['fil'],\n fr: ['fr', 'fr-CA'],\n he: ['he'],\n hr: ['hr'],\n hu: ['hu'],\n id: ['id'],\n it: ['it'],\n ja: ['ja'],\n ko: ['ko'],\n lt: ['lt'],\n lv: ['lv'],\n ms: ['ms'],\n mt: ['mt'],\n nb: ['nb'],\n nl: ['nl'],\n pl: ['pl'],\n pt: ['pt', 'pt-BR'],\n ro: ['ro'],\n ru: ['ru'],\n sk: ['sk'],\n sl: ['sl'],\n sv: ['sv'],\n th: ['th'],\n tr: ['tr'],\n vi: ['vi'],\n zh: ['zh', 'zh-HK', 'zh-TW'],\n};\n","import { supportedLocales } from './stripe-upe-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace(/_/g, '-').toLowerCase().split('-');\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'auto';\n }\n\n const formattedLocale = country ? `${language}-${country.toUpperCase()}` : language;\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { includes, some } from 'lodash';\n\nimport {\n FormattedHostedInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport formatLocale from './format-locale';\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeAdditionalActionRequired,\n StripeElement,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeError,\n StripeEventType,\n StripePaymentMethodType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n StripeUPEInitializationData,\n StripeUpeResult,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst APM_REDIRECT = [\n StripePaymentMethodType.SOFORT,\n StripePaymentMethodType.EPS,\n StripePaymentMethodType.GRABPAY,\n StripePaymentMethodType.BANCONTACT,\n StripePaymentMethodType.IDEAL,\n StripePaymentMethodType.GIROPAY,\n StripePaymentMethodType.ALIPAY,\n StripePaymentMethodType.KLARNA,\n];\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n private stripeUPEIntegrationService: StripeUPEIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeUPEPaymentInitializeOptions,\n ): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._loadStripeElement(stripeupe, gatewayId, methodId).catch((error) =>\n stripeupe.onError?.(error),\n );\n\n this.stripeUPEIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeupe,\n this._stripeElements,\n );\n\n return Promise.resolve();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData, methodId, gatewayId } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const state = this.paymentIntegrationService.getState();\n const { isStoreCreditApplied: useStoreCredit } = state.getCheckoutOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const stripePaymentProviderCustomer = isStripeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const stripeLinkAuthenticationState =\n stripePaymentProviderCustomer.stripeLinkAuthenticationState;\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n if (gatewayId) {\n await this.stripeUPEIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n const { email } = state.getCustomerOrThrow();\n\n if (stripeLinkAuthenticationState !== undefined && !email) {\n const billingAddress = state.getBillingAddressOrThrow();\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n }\n\n if (isVaultedInstrument(paymentData)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n const { initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { newConfirmationFlow } = initializationData || {};\n\n if (newConfirmationFlow) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n if (includes(APM_REDIRECT, methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithAPM(payment.methodId);\n\n return;\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithoutRedirect(\n payment.methodId,\n stripeLinkAuthenticationState ? false : shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this.stripeUPEIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(\n methodId,\n clientToken || '',\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalActionWithStripeConfirmation(\n error,\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _executeWithAPM(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(methodId, paymentMethod.clientToken || '');\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processAdditionalAction(error, methodId);\n }\n }\n\n private async _executeWithoutRedirect(\n methodId: string,\n shouldSaveInstrument: boolean,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentMethod.clientToken || '',\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processAdditionalAction(\n error,\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _executeWithVaulted(\n methodId: string,\n token: string,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const cartId = state.getCart()?.id;\n\n try {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n cart_id: cartId,\n bigpay_token: { token },\n confirm: false,\n client_token: paymentMethod.clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processVaultedAdditionalAction(\n error,\n methodId,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _loadStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const { containerId, style, render, initStripeElementUpdateTrigger } = stripeupe;\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n this._isStripeElementUpdateEnabled =\n !!checkoutSettings.features['PI-1679.trigger_update_stripe_payment_element'] &&\n typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeUPEIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeUPEIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatLocale(shopperLanguage),\n appearance,\n });\n\n const { getBillingAddress, getShippingAddress } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this._stripeElements.getElement(StripeElementType.PAYMENT) ||\n this._stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeUPEIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on('ready', () => {\n render();\n });\n\n stripeElement.on('change', (event: StripeEventType) => {\n if (!event?.value || !('type' in event.value)) {\n return;\n }\n\n this._updateStripeLinkStateByElementType(event.value.type);\n });\n\n if (this._isStripeElementUpdateEnabled) {\n initStripeElementUpdateTrigger?.(this._updateStripeElement.bind(this));\n }\n }\n\n private async _processAdditionalActionWithStripeConfirmation(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { data: additionalActionData } = error.body.additional_action_required;\n const { token } = additionalActionData;\n\n const { paymentIntent } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntent?.id || token,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeUPEClient?.confirmPayment(stripePaymentData)\n : await this._stripeUPEClient?.retrievePaymentIntent(token || '');\n\n stripeError = confirmationResult?.error;\n\n if (stripeError || !confirmationResult?.paymentIntent) {\n throw new PaymentMethodFailedError();\n }\n\n return confirmationResult;\n } catch (error: unknown) {\n this.stripeUPEIntegrationService.throwStripeError(stripeError);\n }\n }\n\n // TODO: complexity of _processAdditionalAction method\n\n private async _processAdditionalAction(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!isRequestError(error)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)) {\n const {\n data: { token, redirect_url },\n } = error.body.additional_action_required;\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n if (\n this.stripeUPEIntegrationService.isRedirectAction(\n error.body.additional_action_required,\n ) &&\n !isPaymentCompleted\n ) {\n const { paymentIntent, error: stripeError } =\n await this._stripeUPEClient.confirmPayment(\n this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n ),\n );\n\n if (stripeError) {\n this.stripeUPEIntegrationService.throwDisplayableStripeError(stripeError);\n throw new PaymentMethodFailedError();\n }\n\n if (!paymentIntent) {\n throw new RequestError();\n }\n } else if (\n this.stripeUPEIntegrationService.isOnPageAdditionalAction(\n error.body.additional_action_required,\n )\n ) {\n let result;\n let catchedConfirmError = false;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n );\n const isPaymentCompleted =\n await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n try {\n result = !isPaymentCompleted\n ? await this._stripeUPEClient.confirmPayment(stripePaymentData)\n : await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this.stripeUPEIntegrationService.throwDisplayableStripeError(result.error);\n\n if (this.stripeUPEIntegrationService.isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n catchedConfirmError ? token : result?.paymentIntent?.id,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n }\n\n throw error;\n }\n\n private async _processVaultedAdditionalAction(\n error: unknown,\n methodId?: string,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !methodId ||\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this._stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this.stripeUPEIntegrationService.throwStripeError(result.error);\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n catchedConfirmError ? clientSecret : result?.paymentIntent?.id,\n false,\n shouldSetAsDefaultInstrument,\n );\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const formattedPayload: StripeUPEIntent & FormattedHostedInstrument = {\n cart_id: cartId,\n credit_card_token: { token },\n confirm: false,\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private _updateStripeElement({ shouldShowTerms }: StripeElementUpdateOptions): void {\n const stripeElement = this._stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.update({\n ...this._getStripeElementTerms(shouldShowTerms),\n });\n }\n\n private _getStripeElementTerms(\n shouldShowTerms?: boolean,\n ): Pick {\n let card = StripeStringConstants.AUTO;\n\n if (this._isStripeElementUpdateEnabled) {\n card = shouldShowTerms ? StripeStringConstants.AUTO : StripeStringConstants.NEVER;\n }\n\n return {\n terms: {\n card,\n },\n };\n }\n\n private _updateStripeLinkStateByElementType(paymentElementType: StripePaymentMethodType): void {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const isStripeLinkElementType = paymentElementType === StripePaymentMethodType.Link;\n\n // INFO: Trigger additional update only if Stripe Link Authentication was skipped on the customer step, but the Link payment element was rendered.\n if (\n !isStripeAcceleratedCheckoutCustomer(paymentProviderCustomer) &&\n isStripeLinkElementType\n ) {\n this.paymentIntegrationService.updatePaymentProviderCustomer({\n stripeLinkAuthenticationState: isStripeLinkElementType,\n });\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeUPEScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeUPEIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe-upe';\n\nexport const isStripePaymentEvent = (event: unknown): event is StripePaymentEvent => {\n return typeof event === 'object' && event !== null && 'value' in event && 'collapsed' in event;\n};\n","import {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport formatLocale from './format-locale';\nimport { isStripePaymentEvent } from './is-stripe-payment-event';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeAdditionalActionRequired,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n StripeUpeResult,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeUPEClient?: StripeUPEClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n private readonly stripeSVGSizeCoefficient = 0.88;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n private stripeUPEIntegrationService: StripeUPEIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeUPEPaymentInitializeOptions,\n ): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n try {\n await this._initializeStripeElement(stripeupe, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeupe.onError?.(error);\n }\n }\n\n this.stripeUPEIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeupe,\n this.stripeElements,\n );\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n const { methodId, gatewayId } = payment || {};\n\n if (!this.stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" or \"methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeUPEIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this.stripeUPEIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n const { containerId, style, render, paymentMethodSelect, handleClosePaymentMethod } =\n stripeupe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatLocale(shopperLanguage),\n appearance: this._getElementAppearance(style),\n fonts: [\n {\n cssSrc: 'https://fonts.googleapis.com/css?family=Montserrat:700,500,400%7CKarla:400&display=swap', // TODO: get style from theme\n },\n ],\n });\n\n const { getBillingAddress, getShippingAddress } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this.stripeElements.getElement(StripeElementType.PAYMENT) ||\n this.stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n layout: {\n type: 'accordion',\n defaultCollapsed: false,\n radios: true,\n spacedAccordionItems: false,\n visibleAccordionItemsCount: 0,\n },\n });\n\n this.stripeUPEIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on('ready', () => {\n render();\n });\n\n stripeElement.on('change', (event: StripeEventType) => {\n this._onStripeElementChange(event, gatewayId, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _getElementAppearance(\n style?: StripeUPEPaymentInitializeOptions['style'],\n ): StripeUPEAppearanceOptions | undefined {\n if (!style) {\n return;\n }\n\n const titleFontSize = '15px'; // TODO: get style from theme\n const titleFontWeight = '700'; // TODO: get style from theme\n const titleColor = '#5f5f5f'; // TODO: get style from theme\n const radioColor = '#ddd'; // TODO: get style from theme\n const radioFocusColor = '#4496f6'; // TODO: get style from theme\n const { radioIconOuterWidth, radioIconOuterStrokeWidth, radioIconInnerWidth } = style;\n const radioIconSize = this._getRadioIconSizes(\n radioIconOuterWidth,\n radioIconOuterStrokeWidth,\n radioIconInnerWidth,\n );\n\n return {\n variables: {\n ...this.stripeUPEIntegrationService.mapAppearanceVariables(style),\n fontFamily: 'Montserrat, Arial, Helvetica', // TODO: get style from theme\n },\n rules: {\n '.Input': this.stripeUPEIntegrationService.mapInputAppearanceRules(style),\n '.AccordionItem': {\n borderRadius: 0,\n borderWidth: 0,\n borderBottomWidth: '1px',\n boxShadow: 'none',\n fontSize: titleFontSize,\n fontWeight: titleFontWeight,\n padding: '13px 20px 13px 18px',\n },\n '.TabLabel, .AccordionItem': {\n fontSize: titleFontSize,\n fontWeight: titleFontWeight,\n color: titleColor,\n },\n '.TabLabel--selected, .AccordionItem--selected': {\n fontWeight: titleFontWeight,\n color: titleColor,\n },\n '.RadioIcon': {\n width: radioIconSize.outerWidth,\n },\n '.RadioIconOuter': {\n strokeWidth: radioIconSize.outerStrokeWidth,\n stroke: radioColor,\n },\n '.RadioIconOuter--checked': {\n stroke: radioFocusColor,\n },\n '.RadioIconInner': {\n r: radioIconSize.innerRadius,\n fill: radioFocusColor,\n },\n },\n };\n }\n\n private _getRadioIconSizes(\n realOuterWidth: string | number = 26,\n realOuterStrokeWidth: string | number = 1,\n realInnerWidth: string | number = 17,\n ) {\n const percentageCoefficient = this.stripeSVGSizeCoefficient * 100;\n\n const outerWidth =\n typeof realOuterWidth === 'string' ? parseInt(realOuterWidth, 10) : realOuterWidth;\n const outerStrokeWidth =\n typeof realOuterStrokeWidth === 'string'\n ? parseInt(realOuterStrokeWidth, 10)\n : realOuterStrokeWidth;\n const innerWidth =\n typeof realInnerWidth === 'string' ? parseInt(realInnerWidth, 10) : realInnerWidth;\n\n const stripeEqualOuterWidth = (outerWidth / this.stripeSVGSizeCoefficient).toFixed(2);\n const stripeEqualOuterStrokeWidth = (\n (outerStrokeWidth / outerWidth) *\n percentageCoefficient\n ).toFixed(2);\n const stripeEqualInnerRadius = (\n ((innerWidth / outerWidth) * percentageCoefficient) /\n 2\n ).toFixed(2);\n\n return {\n outerWidth: `${stripeEqualOuterWidth}px`,\n outerStrokeWidth: `${stripeEqualOuterStrokeWidth}px`,\n innerRadius: `${stripeEqualInnerRadius}px`,\n };\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(methodId: string, token: string): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const formattedPayload = {\n cart_id: cartId,\n credit_card_token: { token },\n confirm: false,\n payment_method_id: this.selectedMethodId,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeUPEClient || !this.stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { data: additionalActionData } = error.body.additional_action_required;\n const { token } = additionalActionData;\n\n const { paymentIntent } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeUPEClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this.stripeUPEClient?.confirmPayment(stripePaymentData)\n : await this.stripeUPEClient?.retrievePaymentIntent(token || '');\n\n stripeError = confirmationResult?.error;\n\n if (stripeError || !confirmationResult?.paymentIntent) {\n throw new PaymentMethodFailedError();\n }\n\n return confirmationResult;\n } catch (error: unknown) {\n this.stripeUPEIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private _onStripeElementChange(\n event: StripeEventType,\n gatewayId: string,\n methodId: string,\n paymentMethodSelect?: (id: string) => void,\n ) {\n if (!isStripePaymentEvent(event) || event.collapsed) {\n return;\n }\n\n this.selectedMethodId = event.value.type;\n paymentMethodSelect?.(`${gatewayId}-${methodId}`);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeUPEScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeUPEIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeupe', id: 'stripe_ocs' },\n]);\n","import { RequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface TdOnlineMartHostWindow extends Window {\n customcheckout?(): TDCustomCheckoutSDK;\n}\n\nexport interface TDCustomCheckoutSDK {\n create(fieldType: FieldType, options?: FieldOptions): TdOnlineMartElement;\n createToken(callback: (result: CreateTokenResponse) => void): void;\n}\n\nexport interface TdOnlineMartElement {\n mount(cssSelector: string): void;\n unmount(): void;\n}\n\nexport enum FieldType {\n CARD_NUMBER = 'card-number',\n CVV = 'cvv',\n EXPIRY = 'expiry',\n}\n\nexport interface TDOnlineMartInput {\n id: string;\n fieldType: FieldType;\n inputElement?: TdOnlineMartElement;\n}\n\ninterface CreateTokenResponse {\n code: string;\n error?: CreateTokenError;\n token?: string;\n last4?: string;\n expiryMonth?: string;\n expiryYear?: string;\n}\n\nexport interface CreateTokenError {\n field: string;\n type: string;\n message: string;\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport interface TdOnlineMartThreeDSErrorBody {\n errors?: Array<{ code: string }>;\n three_ds_result?: {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n };\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type TdOnlineMartAdditionalAction = RequestError;\n\n// Note: The style property affects the remote styling of text inside the iframe input. The classes property updates the class list of the element the field is mounted to on your page.\ninterface FieldOptions {\n placeholder?: string;\n style?: Styles;\n classes?: Classes;\n brands?: string[];\n}\n\ninterface Classes {\n base?: string;\n complete?: string;\n empty?: string;\n focus?: string;\n error?: string;\n}\n\ninterface Styles {\n base?: CssStyles;\n complete?: CssStyles;\n empty?: CssStyles;\n error?: CssStyles;\n}\n\ninterface CssStyles {\n color?: string;\n fontFamily?: string;\n fontSize?: string;\n fontStyle?: string;\n fontWeight?: string;\n textDecoration?: string;\n padding?: string;\n paddingLeft?: string;\n paddingTop?: string;\n paddingRight?: string;\n paddingBottom?: string;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isCreateTokenError from './is-create-token-error';\nimport { isTdOnlineMartAdditionalAction } from './isTdOnlineMartAdditionalAction';\nimport {\n FieldType,\n TDCustomCheckoutSDK,\n TDOnlineMartInput,\n TdOnlineMartThreeDSErrorBody,\n} from './td-online-mart';\nimport TDOnlineMartScriptLoader from './td-online-mart-script-loader';\n\nexport default class TDOnlineMartPaymentStrategy implements PaymentStrategy {\n private tdOnlineMartClient?: TDCustomCheckoutSDK;\n private tdInputs: TDOnlineMartInput[] = [\n {\n id: 'ccNumber',\n fieldType: FieldType.CARD_NUMBER,\n },\n {\n id: 'ccCvv',\n fieldType: FieldType.CVV,\n },\n {\n id: 'ccExpiry',\n fieldType: FieldType.EXPIRY,\n },\n ];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private tdOnlineMartScriptLoader: TDOnlineMartScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.tdOnlineMartClient = await this.loadTDOnlineMartJs();\n\n this.mountHostedFields(methodId);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!payment.methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paymentPayload = await this.getPaymentPayloadOrThrow(payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error: unknown) {\n await this.processWithAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.tdOnlineMartClient = undefined;\n\n this.tdInputs.forEach(({ inputElement }: TDOnlineMartInput) => {\n inputElement?.unmount();\n });\n\n return Promise.resolve();\n }\n\n private async getPaymentPayloadOrThrow(payment: OrderPaymentRequestBody) {\n const { methodId, paymentData } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const commonPaymentData = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n browser_info: getBrowserInfo(),\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n paymentData.instrumentId\n ) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const digitalItemsInCart = !!cart.lineItems.digitalItems.length;\n\n const shouldAddVerificationToken =\n !this.isTrustedVaultingInstrument(paymentData.instrumentId) || digitalItemsInCart;\n\n return {\n methodId,\n paymentData: {\n ...commonPaymentData,\n instrumentId: paymentData.instrumentId,\n ...(shouldAddVerificationToken ? { nonce: paymentData.instrumentId } : {}),\n },\n };\n }\n\n let nonce: string;\n\n try {\n nonce = await this.getTokenOrThrow();\n } catch (error) {\n this.throwTokenizationError(error);\n }\n\n return {\n methodId,\n paymentData: {\n ...commonPaymentData,\n nonce,\n },\n };\n }\n\n private mountHostedFields(methodId: string): void {\n const options = this.getHostedFieldsOptions();\n const tdOnlineMartClient = this.getTDOnlineMartClientOrThrow();\n\n this.tdInputs.forEach((input: TDOnlineMartInput) => {\n const inputId = `${methodId}-${input.id}`;\n\n if (!document.getElementById(inputId)) {\n return;\n }\n\n input.inputElement = tdOnlineMartClient.create(input.fieldType, options);\n input.inputElement.mount(`#${inputId}`);\n });\n }\n\n private async loadTDOnlineMartJs(): Promise {\n if (this.tdOnlineMartClient) {\n return this.tdOnlineMartClient;\n }\n\n return this.tdOnlineMartScriptLoader.load();\n }\n\n private getTokenOrThrow(): Promise {\n return new Promise((resolve, reject) => {\n this.getTDOnlineMartClientOrThrow().createToken((result) => {\n const { error, token } = result;\n\n if (error || !token) {\n return reject(error);\n }\n\n resolve(token);\n });\n });\n }\n\n private getTDOnlineMartClientOrThrow(): TDCustomCheckoutSDK {\n if (!this.tdOnlineMartClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.tdOnlineMartClient;\n }\n\n private async processWithAdditionalAction(error: unknown): Promise {\n if (!isTdOnlineMartAdditionalAction(error)) {\n throw error;\n }\n\n const { three_ds_result: threeDSResult }: TdOnlineMartThreeDSErrorBody = error.body;\n const {\n acs_url: formUrl,\n payer_auth_request: threeDSSessionData,\n merchant_data: creq,\n } = threeDSResult || {};\n\n if (!formUrl || !threeDSSessionData || !creq) {\n throw new PaymentArgumentInvalidError(['formUrl', 'threeDSSessionData', 'creq']);\n }\n\n return new Promise((resolve) => {\n this.formPoster.postForm(\n formUrl,\n {\n threeDSSessionData,\n creq,\n },\n resolve,\n '_top',\n );\n });\n }\n\n private throwTokenizationError(error: unknown): never {\n if (!isCreateTokenError(error)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n throw new Error(error.message);\n }\n\n private getHostedFieldsOptions() {\n const style = {\n error: {\n color: '#d14343',\n },\n };\n\n const classes = {\n error: 'form-input--error',\n };\n\n return {\n style,\n classes,\n };\n }\n\n private isTrustedVaultingInstrument(instrumentId: string): boolean {\n const instruments = this.paymentIntegrationService.getState().getInstruments();\n\n const { trustedShippingAddress } =\n instruments?.find(({ bigpayToken }) => bigpayToken === instrumentId) || {};\n\n return !!trustedShippingAddress;\n }\n}\n","import { isArray, isObject, some } from 'lodash';\n\nimport { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TdOnlineMartAdditionalAction, TdOnlineMartThreeDSErrorBody } from './td-online-mart';\n\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nfunction isTdOnlineMartThreeDSErrorBody(\n errorBody: unknown,\n): errorBody is TdOnlineMartThreeDSErrorBody {\n return (\n isObject(errorBody) &&\n typeof errorBody === 'object' &&\n 'errors' in errorBody &&\n 'three_ds_result' in errorBody &&\n isArray((errorBody as TdOnlineMartThreeDSErrorBody).errors) &&\n some((errorBody as TdOnlineMartThreeDSErrorBody).errors, {\n code: 'three_d_secure_required',\n })\n );\n}\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n\nexport function isTdOnlineMartAdditionalAction(\n error: unknown,\n): error is TdOnlineMartAdditionalAction {\n return isRequestError(error) && isTdOnlineMartThreeDSErrorBody(error.body);\n}\n","import { CreateTokenError } from './td-online-mart';\n\nexport default function isCreateTokenError(error: unknown): error is CreateTokenError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'field' in error &&\n 'type' in error &&\n 'message' in error\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TDCustomCheckoutSDK, TdOnlineMartHostWindow } from './td-online-mart';\n\nexport default class TDOnlineMartScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private tdOnlineMartWindow: TdOnlineMartHostWindow = window,\n ) {}\n\n async load(): Promise {\n if (!this.tdOnlineMartWindow.customcheckout) {\n await this.scriptLoader.loadScript(\n 'https://libs.na.bambora.com/customcheckout/1/customcheckout.js',\n );\n }\n\n if (!this.tdOnlineMartWindow.customcheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.tdOnlineMartWindow.customcheckout();\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport TDOnlineMartPaymentStrategy from './td-online-mart-payment-strategy';\nimport TDOnlineMartScriptLoader from './td-online-mart-script-loader';\n\nconst createTDOnlineMartPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new TDOnlineMartPaymentStrategy(\n paymentIntegrationService,\n new TDOnlineMartScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createTDOnlineMartPaymentStrategy, [{ id: 'tdonlinemart' }]);\n","import { merge, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n WithWorldpayAccessPaymentInitializeOptions,\n WorldpayAccess3DSOptions,\n WorldpayAccessAdditionalAction,\n WorldpayAccessPaymentInitializeOptions,\n} from './worldpayaccess-payment-options';\n\nconst IFRAME_NAME = 'worldpay_hosted_payment_page';\nconst IFRAME_HIDDEN_NAME = 'worldpay_hosted_hidden_payment_page';\nconst PAYMENT_CANNOT_CONTINUE = 'Payment cannot continue';\n\nlet submit: (paymentPayload: OrderPaymentRequestBody) => Promise;\n\nexport default class WorldpayAccessPaymentStrategy extends CreditCardPaymentStrategy {\n private _initializeOptions?: WorldpayAccessPaymentInitializeOptions;\n\n async initialize(\n options?: PaymentInitializeOptions & WithWorldpayAccessPaymentInitializeOptions,\n ): Promise {\n this._initializeOptions = options && options.worldpay;\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return super.initialize(options);\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n submit = this._submitAdditionalAction();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n return await super.execute(orderRequest, options);\n } catch (error) {\n return this._processAdditionalAction(error, payment);\n }\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise((resolve, reject) => {\n const messageEvent = async (event: MessageEvent) => {\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEvent);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n iframeHidden.remove();\n\n const data = JSON.parse(event.data);\n const paymentPayload = merge({}, payment, {\n paymentData: { threeDSecure: { token: data.SessionId } },\n });\n\n try {\n resolve(await submit(paymentPayload));\n } catch (submitError) {\n if (\n !isRequestError(submitError) ||\n !some(submitError.body.errors, { code: 'three_d_secure_required' })\n ) {\n return reject(submitError);\n }\n\n if (!this._initializeOptions) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n const { onLoad } = this._initializeOptions;\n\n const frame = this._createIframe(submitError.body.three_ds_result);\n\n try {\n onLoad(frame, () => reject(new Error('Payment was cancelled')));\n } catch (onLoadError) {\n reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n }\n };\n\n window.addEventListener('message', messageEvent);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEvent);\n throw new Error(PAYMENT_CANNOT_CONTINUE);\n }\n });\n }\n\n private _createHiddenIframe(body: WorldpayAccessAdditionalAction): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n document.body.appendChild(iframe);\n\n if (!iframe.contentWindow) {\n throw new Error();\n }\n\n iframe.id = IFRAME_HIDDEN_NAME;\n iframe.height = '0px';\n iframe.width = '0px';\n\n const form = document.createElement('form');\n const formId = 'collectionForm';\n\n form.id = formId;\n form.name = 'devicedata';\n form.method = 'post';\n\n const url = body.additional_action_required.data.redirect_url;\n\n form.action = url;\n\n const inputBin = document.createElement('input');\n\n inputBin.name = 'Bin';\n inputBin.type = 'hidden';\n inputBin.value = body.provider_data.source_id;\n form.appendChild(inputBin);\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = body.provider_data.data;\n form.appendChild(inputJWT);\n\n const button = document.createElement('button');\n\n button.type = 'submit';\n button.id = 'btnsubmit';\n form.appendChild(button);\n\n if (navigator.userAgent.match('Firefox')) {\n iframe.srcdoc = form.outerHTML;\n } else {\n iframe.contentWindow.document.body.appendChild(form);\n }\n\n const script = document.createElement('script');\n\n script.innerHTML = `\n document.getElementById('${formId}').submit();\n `;\n iframe.contentWindow.document.body.appendChild(script);\n\n return iframe;\n }\n\n private _createIframe(data: WorldpayAccess3DSOptions): HTMLIFrameElement {\n const form = document.createElement('form');\n\n form.id = 'challengeForm';\n form.method = 'POST';\n form.action = data.acs_url;\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = data.payer_auth_request;\n form.appendChild(inputJWT);\n\n const merchant = document.createElement('input');\n\n merchant.name = 'MD';\n merchant.type = 'hidden';\n merchant.value = `merchantSessionId=${data.merchant_data}`;\n form.appendChild(merchant);\n\n const script = document.createElement('script');\n\n script.type = 'text/javascript';\n script.innerHTML =\n \"window.onload = function() { document.getElementById('challengeForm').submit(); }\";\n\n const iframe = document.createElement('iframe');\n\n iframe.name = IFRAME_NAME;\n iframe.height = '400';\n iframe.width = '100%';\n iframe.srcdoc = `${form.outerHTML} ${script.outerHTML}`;\n\n return iframe;\n }\n\n private _submitAdditionalAction() {\n if (this._shouldRenderHostedForm) {\n if (!this._hostedForm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const hostedForm = this._hostedForm;\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await hostedForm.submit(paymentPayload);\n };\n }\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n };\n }\n\n private _isValidJsonWithSessionId(str: string) {\n try {\n const data = JSON.parse(str);\n\n if (data.SessionId) {\n return true;\n }\n\n return false;\n } catch (e) {\n return false;\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessPaymetStrategy from './worldpayaccess-payment-strategy';\n\nconst createWorldpayAccessPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new WorldpayAccessPaymetStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createWorldpayAccessPaymentStrategy, [{ id: 'worldpayaccess' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class StorefrontPaymentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async saveExternalId(methodId: string, token: string): Promise {\n const url = `/api/storefront/payment/${methodId}/save-external-id`;\n const options = {\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n externalId: token,\n provider: methodId,\n },\n };\n\n await this._requestSender.post(url, options);\n }\n}\n","import {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n StorefrontPaymentRequestSender,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class ZipPaymentStrategy implements PaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const { getPaymentMethodOrThrow } = await this.paymentIntegrationService.loadPaymentMethod(\n methodId,\n options,\n );\n\n const {\n clientToken,\n initializationData,\n }: { clientToken?: string; initializationData?: { redirectUrl?: string } } =\n getPaymentMethodOrThrow(methodId);\n const redirectUrl = initializationData?.redirectUrl;\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n await this.paymentIntegrationService.initializePayment(methodId, { useStoreCredit });\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: { nonce },\n });\n } catch (error) {\n if (isRequestError(error) && error.body.status === 'additional_action_required') {\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this.storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n StorefrontPaymentRequestSender,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ZipPaymentStrategy from './zip-payment-strategy';\n\nconst createZipPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const requestSender = createRequestSender({ host: getHost() });\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n return new ZipPaymentStrategy(paymentIntegrationService, storefrontPaymentRequestSender);\n};\n\nexport default toResolvableModule(createZipPaymentStrategy, [{ id: 'zip' }, { id: 'quadpay' }]);\n","import { Action } from '@bigcommerce/data-store';\n\nimport Country from './country';\n\nexport enum CountryActionType {\n LoadCountriesRequested = 'LOAD_COUNTRIES_REQUESTED',\n LoadCountriesSucceeded = 'LOAD_COUNTRIES_SUCCEEDED',\n LoadCountriesFailed = 'LOAD_COUNTRIES_FAILED',\n}\n\nexport type LoadCountriesAction =\n | LoadCountriesRequestedAction\n | LoadCountriesSucceededAction\n | LoadCountriesFailedAction;\n\nexport interface LoadCountriesRequestedAction extends Action {\n type: CountryActionType.LoadCountriesRequested;\n}\n\nexport interface LoadCountriesSucceededAction extends Action {\n type: CountryActionType.LoadCountriesSucceeded;\n}\n\nexport interface LoadCountriesFailedAction extends Action {\n type: CountryActionType.LoadCountriesFailed;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Country from './country';\nimport { CountryActionType } from './country-actions';\nimport CountryRequestSender from './country-request-sender';\n\nexport default class CountryActionCreator {\n constructor(private _countryRequestSender: CountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable> {\n return Observable.create((observer: Observer>) => {\n observer.next(createAction(CountryActionType.LoadCountriesRequested));\n\n this._countryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(CountryActionType.LoadCountriesSucceeded, response.body.data),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CountryActionType.LoadCountriesFailed, response),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { CountryResponseBody } from './country-responses';\n\nexport default class CountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/store/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n PaymentStrategy,\n PaymentStrategyFactory,\n PaymentStrategyResolveId,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories = defaultPaymentStrategyFactories,\n options: { useFallback: boolean } = { useFallback: false },\n): ResolveIdRegistry {\n const { useFallback } = options;\n const registry = new ResolveIdRegistry(useFallback);\n\n for (const [, createPaymentStrategy] of Object.entries(paymentStrategyFactories)) {\n if (\n !isResolvableModule, PaymentStrategyResolveId>(\n createPaymentStrategy,\n )\n ) {\n continue;\n }\n\n for (const resolverId of createPaymentStrategy.resolveIds) {\n registry.register(resolverId, () => createPaymentStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","enum PaymentStrategyType {\n ADYENV2 = 'adyenv2',\n ADYENV2_GOOGLEPAY = 'googlepayadyenv2',\n ADYENV3 = 'adyenv3',\n ADYENV3_GOOGLEPAY = 'googlepayadyenv3',\n AFFIRM = 'affirm',\n AFTERPAY = 'afterpay',\n AUTHORIZENET_GOOGLE_PAY = 'googlepayauthorizenet',\n AMAZONPAY = 'amazonpay',\n APPLEPAY = 'applepay',\n BARCLAYS = 'barclays',\n BLUESNAPV2 = 'bluesnapv2',\n BOLT = 'bolt',\n CBA_MPGS = 'cba_mpgs',\n CHECKOUTCOM = 'checkoutcom',\n CHECKOUTCOM_APM = 'checkoutcomapm',\n CHECKOUTCOM_FAWRY = 'checkoutcomfawry',\n CHECKOUTCOM_SEPA = 'checkoutcomsepa',\n CHECKOUTCOM_IDEAL = 'checkoutcomideal',\n CREDIT_CARD = 'creditcard',\n CHECKOUTCOM_GOOGLE_PAY = 'googlepaycheckoutcom',\n CLEARPAY = 'clearpay',\n CONVERGE = 'converge',\n CYBERSOURCE = 'cybersource',\n CYBERSOURCEV2 = 'cybersourcev2',\n BNZ = 'bnz',\n BNZ_GOOGLEPAY = 'googlepaybnz',\n DIGITALRIVER = 'digitalriver',\n CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LAYBUY = 'laybuy',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\n OPY = 'opy',\n ORBITAL_GOOGLE_PAY = 'googlepayorbital',\n PAYPAL_EXPRESS = 'paypalexpress',\n PAYPAL_EXPRESS_CREDIT = 'paypalexpresscredit',\n PAYPAL_COMMERCE = 'paypalcommerce',\n PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit',\n PAYPAL_COMMERCE_CREDIT_CARD = 'paypalcommercecreditcards',\n PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods',\n PAYPAL_COMMERCE_VENMO = 'paypalcommercevenmo',\n PPSDK = 'PAYMENT_TYPE_SDK',\n QUADPAY = 'quadpay',\n SAGE_PAY = 'sagepay',\n SQUARE = 'squarev2',\n STRIPEV3 = 'stripev3',\n STRIPE_UPE = 'stripeupe',\n STRIPE_UPE_GOOGLE_PAY = 'googlepaystripeupe',\n BRAINTREE = 'braintree',\n BRAINTREE_PAYPAL = 'braintreepaypal',\n BRAINTREE_VENMO = 'braintreevenmo',\n BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n BRAINTREE_VISA_CHECKOUT = 'braintreevisacheckout',\n BRAINTREE_GOOGLE_PAY = 'googlepaybraintree',\n WE_PAY = 'wepay',\n WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n MASTERPASS = 'masterpass',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { PaymentStrategy as PaymentStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from './payment-request-options';\nimport {\n PaymentStrategyActionType,\n PaymentStrategyDeinitializeAction,\n PaymentStrategyExecuteAction,\n PaymentStrategyFinalizeAction,\n PaymentStrategyInitializeAction,\n PaymentStrategyWidgetAction,\n} from './payment-strategy-actions';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyRegistryV2 from './payment-strategy-registry-v2';\nimport PaymentStrategyType from './payment-strategy-type';\nimport PaymentStrategyWidgetActionCreator from './payment-strategy-widget-action-creator';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyActionCreator {\n private _paymentStrategyWidgetActionCreator: PaymentStrategyWidgetActionCreator;\n\n constructor(\n private _strategyRegistry: PaymentStrategyRegistry,\n private _strategyRegistryV2: PaymentStrategyRegistryV2,\n private _orderActionCreator: OrderActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {\n this._paymentStrategyWidgetActionCreator = new PaymentStrategyWidgetActionCreator();\n }\n\n execute(\n payload: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n const { payment = {} as OrderPaymentRequestBody, useStoreCredit } = payload;\n const meta = { methodId: payment.methodId };\n\n return (store) => {\n const { checkout } = store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n return concat(\n shouldExecuteSpamCheck\n ? this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(store)\n : empty(),\n of(createAction(PaymentStrategyActionType.ExecuteRequested, undefined, meta)),\n defer(() => {\n const state = store.getState();\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n if (state.payment.isPaymentDataRequired(useStoreCredit)) {\n const method = state.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n strategy = this._getStrategy(method);\n } else {\n strategy = this._strategyRegistryV2.get({\n id: PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED,\n });\n }\n\n const promise: Promise = strategy.execute(\n payload,\n {\n ...options,\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n },\n );\n\n return promise.then(() =>\n createAction(PaymentStrategyActionType.ExecuteSucceeded, undefined, meta),\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.ExecuteFailed, error, meta),\n ),\n );\n };\n }\n\n finalize(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentStrategyActionType.FinalizeRequested)),\n this._loadOrderPaymentsIfNeeded(store, options),\n defer(async () => {\n const state = store.getState();\n const { providerId = '', gatewayId = '' } = state.payment.getPaymentId() || {};\n const method = state.paymentMethods.getPaymentMethod(providerId, gatewayId);\n\n if (!method) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const strategy = this._getStrategy(method);\n\n await strategy.finalize({\n ...options,\n methodId: method.id,\n gatewayId: method.gateway,\n });\n\n return createAction(PaymentStrategyActionType.FinalizeSucceeded, undefined, {\n methodId: method.id,\n });\n }),\n ).pipe(\n catchError((error) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n\n return throwErrorAction(PaymentStrategyActionType.FinalizeFailed, error, {\n methodId: payment && payment.providerId,\n });\n }),\n );\n }\n\n initialize(\n options: PaymentInitializeOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.initialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.InitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.InitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.InitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n deinitialize(\n options: PaymentRequestOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && !state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.deinitialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.DeinitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.DeinitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n return this._paymentStrategyWidgetActionCreator.widgetInteraction(method, options);\n }\n\n private _getStrategy(method: PaymentMethod): PaymentStrategy | PaymentStrategyV2 {\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._strategyRegistry.getByMethod(method);\n } catch {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n }\n\n return strategy;\n }\n\n private _loadOrderPaymentsIfNeeded(\n store: ReadableCheckoutStore,\n options?: RequestOptions,\n ): Observable {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (checkout && checkout.orderId) {\n return this._orderActionCreator.loadOrderPayments(checkout.orderId, options);\n }\n\n return empty();\n }\n}\n","import { default as storage } from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private _namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = storage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n // Clean up invalid values\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return storage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return storage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this._namespace}.${key}`;\n }\n}\n","export const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","import PaymentMethod from './payment-method';\nimport PaymentStrategyType from './payment-strategy-type';\n\ntype PPSDKRequiredProperties = 'initializationStrategy';\n\nexport type PPSDKPaymentMethod = PaymentMethod & {\n type: PaymentStrategyType.PPSDK;\n} & Required>;\n\nexport const isPPSDKPaymentMethod = (\n paymentMethod: PaymentMethod,\n): paymentMethod is PPSDKPaymentMethod => {\n const { type, initializationStrategy } = paymentMethod;\n\n return type === PaymentStrategyType.PPSDK && typeof initializationStrategy?.type === 'string';\n};\n","import { InvalidArgumentError } from '../common/error/errors';\nimport { Registry, RegistryOptions } from '../common/registry';\n\nimport PaymentMethod from './payment-method';\nimport * as paymentMethodTypes from './payment-method-types';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { isPPSDKPaymentMethod } from './ppsdk-payment-method';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyRegistry extends Registry<\n PaymentStrategy,\n PaymentStrategyType\n> {\n getByMethod(paymentMethod?: PaymentMethod): PaymentStrategy {\n if (!paymentMethod) {\n return this.get();\n }\n\n const token = this._getToken(paymentMethod);\n\n const cacheToken = [paymentMethod.gateway, paymentMethod.id]\n .filter((value) => value !== undefined && value !== null)\n .join('-');\n\n return this.get(token, cacheToken);\n }\n\n private _getToken(paymentMethod: PaymentMethod): PaymentStrategyType {\n if (isPPSDKPaymentMethod(paymentMethod)) {\n return PaymentStrategyType.PPSDK;\n }\n\n if (paymentMethod.gateway === 'klarna') {\n return PaymentStrategyType.KLARNAV2;\n }\n\n const methodId = paymentMethod.gateway || paymentMethod.id;\n\n if (this._hasFactoryForMethod(methodId)) {\n return methodId;\n }\n\n if (paymentMethod.type === paymentMethodTypes.OFFLINE) {\n return PaymentStrategyType.OFFLINE;\n }\n\n throw new InvalidArgumentError(`'${methodId}' is not registered.`);\n }\n\n private _hasFactoryForMethod(methodId: string): methodId is PaymentStrategyType {\n return this._hasFactory(methodId);\n }\n}\n\nexport interface PaymentStrategyRegistryOptions extends RegistryOptions {\n clientSidePaymentProviders?: string[];\n}\n","import { InvalidArgumentError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import { isNil, values } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve(this._store.getState());\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._hostedFormFactory.create(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return this._store.getState();\n });\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n protected _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n protected _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return form\n .validate()\n .then(() => this._store.dispatch(this._orderActionCreator.submitOrder(order, options)))\n .then(() => form.submit(payment))\n .then(() => this._store.dispatch(this._orderActionCreator.loadCurrentOrder()));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(options?: PaymentInitializeOptions): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BarclaysPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BNZPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const { methodId } = payload.payment;\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { BraintreeError } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeFormErrorsData, BraintreeVerifyPayload } from './braintree';\n\n/**\n * A set of options that are required to initialize the Braintree payment\n * method. You need to provide the options if you want to support 3D Secure\n * authentication flow.\n *\n * ```html\n * \n *
\n *
\n *
\n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * braintree: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * },\n * },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * creditCard: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * styles: {\n * default: {\n * color: '#000',\n * },\n * error: {\n * color: '#f00',\n * },\n * focus: {\n * color: '#0f0',\n * },\n * },\n * onBlur({ fieldType }) {\n * console.log(fieldType);\n * },\n * onFocus({ fieldType }) {\n * console.log(fieldType);\n * },\n * onEnter({ fieldType }) {\n * console.log(fieldType);\n * },\n * onCardTypeChange({ cardType }) {\n * console.log(cardType);\n * },\n * onValidate({ errors, isValid }) {\n * console.log(errors);\n * console.log(isValid);\n * },\n * },\n * },\n * });\n * ```\n */\nexport interface BraintreePaymentInitializeOptions {\n /**\n * The CSS selector of a container where the payment widget should be inserted into.\n */\n containerId?: string;\n\n threeDSecure?: BraintreeThreeDSecureOptions;\n\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n form?: BraintreeFormOptions;\n\n /**\n * The location to insert the Pay Later Messages.\n */\n bannerContainerId?: string;\n\n /**\n * A callback right before render Smart Payment Button that gets called when\n * Smart Payment Button is eligible. This callback can be used to hide the standard submit button.\n */\n onRenderButton?(): void;\n\n /**\n * A callback for submitting payment form that gets called\n * when buyer approved PayPal account.\n */\n submitForm?(): void;\n\n /**\n * A callback that gets called if unable to submit payment.\n *\n * @param error - The error object describing the failure.\n */\n onPaymentError?(error: BraintreeError | StandardError): void;\n\n /**\n * A callback for displaying error popup. This callback requires error object as parameter.\n */\n onError?(error: unknown): void;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\nexport interface BraintreeThreeDSecureOptions {\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param error - Any error raised during the verification process;\n * undefined if there is none.\n * @param iframe - The iframe element containing the verification web page\n * provided by the card issuer.\n * @param cancel - A function, when called, will cancel the verification\n * process and remove the iframe.\n */\n addFrame(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n\n /**\n * A callback that gets called when the iframe is about to be removed from\n * the current page.\n */\n removeFrame(): void;\n challengeRequested?: boolean;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n}\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return !!(fields as BraintreeFormFieldsMap).cardNumber;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n (fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification\n );\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return (error as BraintreeError).name === 'BraintreeError';\n}\n","import { BraintreeHostedFormError } from './braintree';\nimport isBraintreeError from './is-braintree-error';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: any): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport function isBraintreeHostedFormError(error: any): error is BraintreeHostedFormError {\n if (!isBraintreeError(error)) {\n return false;\n }\n\n const { details } = error;\n\n return (\n details === undefined ||\n (typeof details === 'object' &&\n details !== null &&\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys((details as { invalidFieldKeys?: unknown }).invalidFieldKeys)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails } from '../../errors';\n\nimport {\n BraintreeBillingAddressRequestData,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n TokenizationPayload,\n} from './braintree';\nimport {\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeStoredCardFieldsMap,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { isBraintreeFormFieldsMap } from './is-braintree-form-fields-map';\nimport { isBraintreeHostedFormError } from './is-braintree-hosted-form-error';\n\nenum BraintreeHostedFormType {\n CreditCard,\n StoredCardVerification,\n}\n\nexport default class BraintreeHostedForm {\n private _cardFields?: BraintreeHostedFields;\n private _formOptions?: BraintreeFormOptions;\n private _type?: BraintreeHostedFormType;\n private _isInitializedHostedForm = false;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n async initialize(options: BraintreeFormOptions): Promise {\n this._formOptions = options;\n\n this._type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this._mapFieldOptions(options.fields);\n\n if (isEmpty(fields)) {\n this._isInitializedHostedForm = false;\n\n return;\n }\n\n this._cardFields = await this._braintreeSDKCreator.createHostedFields({\n fields,\n styles: options.styles && this._mapStyleOptions(options.styles),\n });\n\n this._cardFields.on('blur', this._handleBlur);\n this._cardFields.on('focus', this._handleFocus);\n this._cardFields.on('cardTypeChange', this._handleCardTypeChange);\n this._cardFields.on('validityChange', this._handleValidityChange);\n this._cardFields.on('inputSubmitRequest', this._handleInputSubmitRequest);\n\n this._isInitializedHostedForm = true;\n }\n\n isInitialized(): boolean {\n return !!this._isInitializedHostedForm;\n }\n\n async deinitialize(): Promise {\n this._isInitializedHostedForm = false;\n\n await this._cardFields?.teardown();\n }\n\n validate() {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const braintreeHostedFormState = this._cardFields.getState();\n\n if (!this._isValidForm(braintreeHostedFormState)) {\n this._handleValidityChange(braintreeHostedFormState);\n\n const errors = this._mapValidationErrors(braintreeHostedFormState.fields);\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n async tokenize(billingAddress: Address): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const tokenizationPayload = await this._cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this._mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return {\n nonce: tokenizationPayload.nonce,\n bin: tokenizationPayload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this._mapTokenizeError(error);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async tokenizeForStoredCardVerification(): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const tokenizationPayload = await this._cardFields.tokenize();\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return {\n nonce: tokenizationPayload.nonce,\n bin: tokenizationPayload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this._mapTokenizeError(error, true);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n private _mapBillingAddress(billingAddress: Address): BraintreeBillingAddressRequestData {\n return {\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n };\n }\n\n private _mapFieldOptions(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n },\n expirationDate: {\n container: `#${fields.cardExpiry.containerId}`,\n placeholder: fields.cardExpiry.placeholder,\n internalLabel: fields.cardExpiry.accessibilityLabel,\n },\n cvv: fields.cardCode && {\n container: `#${fields.cardCode.containerId}`,\n placeholder: fields.cardCode.placeholder,\n internalLabel: fields.cardCode.accessibilityLabel,\n },\n cardholderName: {\n container: `#${fields.cardName.containerId}`,\n placeholder: fields.cardName.placeholder,\n internalLabel: fields.cardName.accessibilityLabel,\n },\n },\n isNil,\n );\n }\n\n return omitBy(\n {\n number: fields.cardNumberVerification && {\n container: `#${fields.cardNumberVerification.containerId}`,\n placeholder: fields.cardNumberVerification.placeholder,\n },\n cvv: fields.cardCodeVerification && {\n container: `#${fields.cardCodeVerification.containerId}`,\n placeholder: fields.cardCodeVerification.placeholder,\n },\n },\n isNil,\n );\n }\n\n private _mapStyleOptions(\n options: BraintreeFormFieldStylesMap,\n ): BraintreeHostedFieldsCreatorConfig['styles'] {\n const mapStyles = (styles: BraintreeFormFieldStyles = {}) =>\n omitBy(\n {\n color: styles.color,\n 'font-family': styles.fontFamily,\n 'font-size': styles.fontSize,\n 'font-weight': styles.fontWeight,\n },\n isNil,\n ) as Dictionary;\n\n return {\n input: mapStyles(options.default),\n '.invalid': mapStyles(options.error),\n ':focus': mapStyles(options.focus),\n };\n }\n\n private _mapFieldType(type: string): BraintreeFormFieldType {\n switch (type) {\n case 'number':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardNumberVerification\n : BraintreeFormFieldType.CardNumber;\n\n case 'expirationDate':\n return BraintreeFormFieldType.CardExpiry;\n\n case 'cvv':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardCodeVerification\n : BraintreeFormFieldType.CardCode;\n\n case 'cardholderName':\n return BraintreeFormFieldType.CardName;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private _mapErrors(fields: BraintreeHostedFieldsState['fields']): BraintreeFormErrorsData {\n const errors: BraintreeFormErrorsData = {};\n\n if (fields) {\n for (const [key, value] of Object.entries(fields)) {\n if (value && this._isValidParam(key)) {\n const { isValid, isEmpty, isPotentiallyValid } = value;\n\n errors[key] = {\n isValid,\n isEmpty,\n isPotentiallyValid,\n };\n }\n }\n }\n\n return errors;\n }\n\n private _mapValidationErrors(\n fields: BraintreeHostedFieldsState['fields'],\n ): BraintreeFormFieldValidateEventData['errors'] {\n return (Object.keys(fields) as Array).reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid\n ? undefined\n : [this._createInvalidError(this._mapFieldType(fieldKey))],\n }),\n {},\n );\n }\n\n private _mapTokenizeError(\n error: BraintreeHostedFormError,\n isStoredCard = false,\n ): BraintreeFormFieldValidateEventData['errors'] | undefined {\n if (error.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {\n const cvvValidation = {\n [this._mapFieldType('cvv')]: [this._createRequiredError(this._mapFieldType('cvv'))],\n };\n\n const expirationDateValidation = {\n [this._mapFieldType('expirationDate')]: [\n this._createRequiredError(this._mapFieldType('expirationDate')),\n ],\n };\n\n const cardNumberValidation = {\n [this._mapFieldType('number')]: [\n this._createRequiredError(this._mapFieldType('number')),\n ],\n };\n\n const cardNameValidation = {\n [this._mapFieldType('cardholderName')]: [\n this._createRequiredError(this._mapFieldType('cardholderName')),\n ],\n };\n\n return isStoredCard\n ? cvvValidation\n : {\n ...cvvValidation,\n ...expirationDateValidation,\n ...cardNumberValidation,\n ...cardNameValidation,\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: [\n this._createInvalidError(this._mapFieldType(fieldKey)),\n ],\n }),\n {},\n );\n }\n\n private _createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'CVV is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Credit card number is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Expiration date is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Full name is required',\n type: 'required',\n };\n\n default:\n return {\n fieldType,\n message: 'Field is required',\n type: 'required',\n };\n }\n }\n\n private _createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Invalid card name',\n type: 'invalid_card_name',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private _handleBlur: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onBlur?.({\n fieldType: this._mapFieldType(event.emittedBy),\n errors: this._mapErrors(event.fields),\n });\n };\n\n private _handleFocus: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onFocus?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleCardTypeChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onCardTypeChange?.({\n cardType:\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master\\-card$/, 'mastercard',) /* eslint-disable-line */\n : undefined,\n });\n };\n\n private _handleInputSubmitRequest: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onEnter?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleValidityChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onValidate?.({\n isValid: this._isValidForm(event),\n errors: this._mapValidationErrors(event.fields),\n });\n };\n\n private _isValidForm(event: BraintreeHostedFieldsState): boolean {\n return (\n Object.keys(event.fields) as Array\n ).every((key) => event.fields[key]?.isValid);\n }\n\n private _isValidParam(\n formErrorDataKey: string,\n ): formErrorDataKey is BraintreeFormErrorDataKeys {\n switch (formErrorDataKey) {\n case 'number':\n case 'cvv':\n case 'expirationDate':\n case 'postalCode':\n case 'cardholderName':\n case 'cardType':\n return true;\n\n default:\n return false;\n }\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","import { isEmpty } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderPaymentRequestBody } from '../../../order';\nimport {\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n} from '../../errors';\nimport { CreditCardInstrument, NonceInstrument } from '../../payment';\n\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeRequestData,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVerifyPayload,\n TokenizationPayload,\n} from './braintree';\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport {\n BraintreeFormOptions,\n BraintreePaymentInitializeOptions,\n BraintreeThreeDSecureOptions,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport isCreditCardInstrumentLike from './is-credit-card-instrument-like';\n\nexport default class BraintreePaymentProcessor {\n private _threeDSecureOptions?: BraintreeThreeDSecureOptions;\n\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n initialize(clientToken: string, options?: BraintreePaymentInitializeOptions): void {\n this._braintreeSDKCreator.initialize(clientToken);\n this._threeDSecureOptions = options?.threeDSecure;\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n preloadPaypalCheckout(\n paypalCheckoutConfig: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ) {\n return this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutConfig,\n onSuccess,\n onError,\n );\n }\n\n async tokenizeCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n ): Promise {\n const { paymentData } = payment;\n\n if (!isCreditCardInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const errors = this._getErrorsRequiredFields(paymentData);\n\n if (!isEmpty(errors)) {\n throw new PaymentInvalidFormError(errors);\n }\n\n const requestData = this._mapToCreditCard(paymentData, billingAddress);\n const client = await this._braintreeSDKCreator.getClient();\n const { creditCards } = await client.request(requestData);\n\n return {\n nonce: creditCards[0].nonce,\n bin: creditCards[0].details?.bin,\n };\n }\n\n async verifyCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n amount: number,\n ): Promise {\n const tokenizationPayload = await this.tokenizeCard(payment, billingAddress);\n\n return this.challenge3DSVerification(tokenizationPayload, amount);\n }\n\n getSessionId(): Promise {\n return this._braintreeSDKCreator.getDataCollector().then(({ deviceData }) => deviceData);\n }\n\n /**\n * @deprecated Use getSessionId() and combine them in the consumer.\n */\n appendSessionId(processedPayment: Promise): Promise {\n return processedPayment\n .then((paymentData) =>\n Promise.all([paymentData, this._braintreeSDKCreator.getDataCollector()]),\n )\n .then(([paymentData, { deviceData }]) => ({\n ...paymentData,\n deviceSessionId: deviceData,\n }));\n }\n\n async initializeHostedForm(options: BraintreeFormOptions): Promise {\n return this._braintreeHostedForm.initialize(options);\n }\n\n validateHostedForm() {\n return this._braintreeHostedForm.validate();\n }\n\n isInitializedHostedForm(): boolean {\n return this._braintreeHostedForm.isInitialized();\n }\n\n async deinitializeHostedForm(): Promise {\n await this._braintreeHostedForm.deinitialize();\n }\n\n tokenizeHostedForm(billingAddress: Address): Promise {\n return this._braintreeHostedForm.tokenize(billingAddress);\n }\n\n tokenizeHostedFormForStoredCardVerification(): Promise {\n return this._braintreeHostedForm.tokenizeForStoredCardVerification();\n }\n\n async verifyCardWithHostedForm(\n billingAddress: Address,\n amount: number,\n ): Promise {\n const tokenizationPayload = await this._braintreeHostedForm.tokenize(billingAddress);\n\n return this.challenge3DSVerification(tokenizationPayload, amount);\n }\n\n async challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this._braintreeSDKCreator.get3DS();\n\n return this._present3DSChallenge(threeDSecure, amount, tokenizationPayload);\n }\n\n async getVenmoCheckout(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeSDKCreator.getVenmoCheckout(resolve, reject);\n });\n }\n\n private _getErrorsRequiredFields(\n paymentData: CreditCardInstrument,\n ): PaymentInvalidFormErrorDetails {\n const { ccNumber, ccExpiry } = paymentData;\n const errors: PaymentInvalidFormErrorDetails = {};\n\n if (!ccNumber) {\n errors.ccNumber = [\n {\n message: 'Credit card number is required',\n type: 'required',\n },\n ];\n }\n\n if (!ccExpiry) {\n errors.ccExpiry = [\n {\n message: 'Expiration date is required',\n type: 'required',\n },\n ];\n }\n\n return errors;\n }\n\n private _present3DSChallenge(\n threeDSecure: BraintreeThreeDSecure,\n amount: number,\n tokenizationPayload: TokenizationPayload,\n ): Promise {\n const { nonce, bin } = tokenizationPayload;\n\n if (!this._threeDSecureOptions || !nonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n addFrame,\n removeFrame,\n challengeRequested = true,\n additionalInformation,\n } = this._threeDSecureOptions;\n const cancelVerifyCard = async () => {\n const response = await threeDSecure.cancelVerifyCard();\n\n verification.cancel(new PaymentMethodCancelledError());\n\n return response;\n };\n\n const roundedAmount = amount.toFixed(2);\n\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n addFrame: (error, iframe) => {\n addFrame(error, iframe, cancelVerifyCard);\n },\n amount: Number(roundedAmount),\n bin,\n challengeRequested,\n nonce,\n removeFrame,\n onLookupComplete: (_data, next) => {\n next();\n },\n collectDeviceData: true,\n additionalInformation,\n }),\n );\n\n return verification.promise;\n }\n\n private _mapToCreditCard(\n creditCard: CreditCardInstrument,\n billingAddress?: Address,\n ): BraintreeRequestData {\n return {\n data: {\n creditCard: {\n cardholderName: creditCard.ccName,\n number: creditCard.ccNumber,\n cvv: creditCard.ccCvv,\n expirationDate: `${creditCard.ccExpiry.month}/${creditCard.ccExpiry.year}`,\n options: {\n validate: false,\n },\n billingAddress: billingAddress && {\n countryCodeAlpha2: billingAddress.countryCode,\n locality: billingAddress.city,\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n },\n },\n },\n endpoint: 'payment_methods/credit_cards',\n method: 'post',\n };\n }\n}\n","import { CreditCardInstrument } from '../../payment';\n\nexport default function isCreditCardInstrumentLike(\n instrument: any,\n): instrument is CreditCardInstrument {\n return (\n instrument &&\n typeof instrument.ccExpiry === 'object' &&\n typeof instrument.ccNumber === 'string' &&\n typeof instrument.ccName === 'string'\n );\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { isHostedInstrumentLike, PaymentMethod } from '../../index';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { PaymentInstrument, PaymentInstrumentMeta } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreePaymentProcessor from './braintree-payment-processor';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private _is3dsEnabled?: boolean;\n private _isHostedFormInitialized?: boolean;\n private _deviceSessionId?: string;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n private _braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this._paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken, braintree);\n\n if (this._isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this._braintreePaymentProcessor.initializeHostedForm(braintree.form);\n this._isHostedFormInitialized =\n this._braintreePaymentProcessor.isInitializedHostedForm();\n }\n\n this._is3dsEnabled = this._paymentMethod.config.is3dsEnabled;\n this._deviceSessionId = await this._braintreePaymentProcessor.getSessionId();\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n if (this._shouldInitializeBraintreeFastlane()) {\n await this._initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this._handleError(error);\n }\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this._isHostedFormInitialized) {\n this._braintreePaymentProcessor.validateHostedForm();\n }\n\n const {\n billingAddress: { getBillingAddressOrThrow },\n order: { getOrderOrThrow },\n } = await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const billingAddress = getBillingAddressOrThrow();\n const orderAmount = getOrderOrThrow().orderAmount;\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: this._isHostedFormInitialized\n ? await this._prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this._preparePaymentData(payment, billingAddress, orderAmount),\n }),\n );\n } catch (error) {\n return this._processAdditionalAction(error, payment, orderAmount);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this._isHostedFormInitialized = false;\n\n await Promise.all([\n this._braintreePaymentProcessor.deinitialize(),\n this._braintreePaymentProcessor.deinitializeHostedForm(),\n ]);\n\n return this._store.getState();\n }\n\n private _handleError(error: unknown): never {\n if (error instanceof Error && error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n return {\n ...commonPaymentData,\n ...paymentData,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCard(payment, billingAddress, orderAmount)\n : await this._braintreePaymentProcessor.tokenizeCard(payment, billingAddress);\n\n return {\n ...commonPaymentData,\n nonce,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n private async _prepareHostedPaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n const { nonce } =\n await this._braintreePaymentProcessor.tokenizeHostedFormForStoredCardVerification();\n\n return {\n ...commonPaymentData,\n ...paymentData,\n nonce,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCardWithHostedForm(\n billingAddress,\n orderAmount,\n )\n : await this._braintreePaymentProcessor.tokenizeHostedForm(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this._handleError(error);\n }\n\n try {\n const {\n instruments: { getCardInstrumentOrThrow },\n } = this._store.getState();\n const { payer_auth_request: storedCreditCardNonce } = error.body.three_ds_result || {};\n const { paymentData } = payment;\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this._braintreePaymentProcessor.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce,\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n deviceSessionId: this._deviceSessionId,\n nonce,\n },\n }),\n );\n } catch (error) {\n return this._handleError(error);\n }\n }\n\n private _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isSubmittingWithStoredCard(payment: OrderPaymentRequestBody): boolean {\n return !!(payment.paymentData && isVaultedInstrument(payment.paymentData));\n }\n\n private _shouldPerform3DSVerification(payment: OrderPaymentRequestBody): boolean {\n return !!(this._is3dsEnabled && !this._isSubmittingWithStoredCard(payment));\n }\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n private _shouldInitializeBraintreeFastlane() {\n const state = this._store.getState();\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const isAcceleratedCheckoutEnabled =\n this._paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return (\n isAcceleratedCheckoutEnabled && !braintreePaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n private async _initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeIntegrationService.initialize(clientToken);\n\n await this._braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError, BraintreeTokenizePayload, BraintreeVenmoCheckout } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private _braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._initializeBraintreeVenmo(paymentMethod);\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this._preparePaymentData(payment);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentData),\n );\n } catch (error) {\n this._handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._braintreePaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n private _handleError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _initializeBraintreeVenmo(paymentMethod: PaymentMethod): Promise {\n const { clientToken } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken);\n this._braintreeVenmoCheckout = await this._braintreePaymentProcessor.getVenmoCheckout();\n } catch (error) {\n this._handleError(error);\n }\n }\n\n private async _preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const { nonce } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this._formattedPayload(nonce) };\n }\n\n const tokenizeResult = await this._braintreeVenmoTokenize();\n const sessionId = await this._braintreePaymentProcessor.getSessionId();\n\n return {\n ...payment,\n paymentData: this._formattedPayload(\n tokenizeResult.nonce,\n tokenizeResult.details.email,\n sessionId,\n ),\n };\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _braintreeVenmoTokenize(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeVenmoCheckout?.tokenize(\n (error: BraintreeError | undefined, payload: BraintreeTokenizePayload) => {\n if (error) {\n return reject(error);\n }\n\n resolve(payload);\n },\n );\n });\n }\n}\n","import { noop } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\nimport { VisaCheckoutPaymentSuccessPayload } from './visacheckout';\nimport VisaCheckoutScriptLoader from './visacheckout-script-loader';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { clientToken, config } = this._paymentMethod || {};\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onError = noop, onPaymentSelect = noop } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: false,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(config?.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n clientToken,\n initOptions,\n ),\n ]).then(([visaCheckout, visaInitOptions]) => {\n visaCheckout.init(visaInitOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload)\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n });\n })\n .then(() => this._store.getState());\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.nonce\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this._paymentMethod.initializationData;\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: { nonce },\n }),\n ),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(() =>\n Promise.all([\n this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n ),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n ),\n ]),\n );\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { InstrumentSelector } from '../../instrument';\nimport isCreditCardLike from '../../is-credit-card-like';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (error) {\n if (\n error instanceof RequestError &&\n some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = error.body.three_ds_result;\n const token = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return await this._submitPayment(payment, { token }, hostedForm);\n }\n\n throw error;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._store.getState();\n const billingAddress = store.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = store.shippingAddress.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.checkout.getCheckoutOrThrow();\n const id = store.order.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: InstrumentSelector['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardLike(paymentData) && paymentData.ccNumber;\n const bin = instrument ? instrument.iin : hostedForm ? hostedForm.getBin() : ccNumber;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument, PaymentInstrument } from './payment';\n\nexport default function isCreditCardLike(\n instrument: PaymentInstrument,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '../../payment';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted](setupCompleteData: CardinalSetupCompletedData): void;\n [CardinalEventType.Validated](data: CardinalValidatedData, jwt?: string): void;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { CreditCardInstrument, ThreeDSecureToken, VaultedInstrument } from '../../payment';\nimport { ThreeDsResult } from '../../payment-response-body';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(() => {});\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(() => {}),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if a payment method explicitly returns a declined error and\n * the shopper has to choose a different payment method if they wish to continue\n * their checkout process.\n */\nexport default class PaymentMethodDeclinedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'The selected payment method was declined. Please select another payment method.',\n );\n\n this.name = 'PaymentMethodDeclinedError';\n this.type = 'payment_declined';\n }\n}\n","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\n","import { noop, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodDeclinedError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n RestApiResponse,\n THREE_D_SECURE_AVAILABLE,\n THREE_D_SECURE_BUSY,\n THREE_D_SECURE_PROCEED,\n ThreeDSjs,\n} from './cba-mpgs';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private _threeDSjs?: ThreeDSjs;\n private _sessionId = '';\n\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _CBAMGPSScriptLoader: CBAMPGSScriptLoader,\n private _locale: string,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n clientToken,\n initializationData: { isTestModeFlagEnabled = false, merchantId },\n config: { is3dsEnabled },\n } = paymentMethod;\n\n if (is3dsEnabled) {\n this._threeDSjs = await this._CBAMGPSScriptLoader.load(isTestModeFlagEnabled);\n\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!clientToken || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._sessionId = clientToken;\n\n await this._threeDSjs.configure({\n merchantId,\n sessionId: this._sessionId,\n callback: () => {\n if (this._threeDSjs?.isConfigured()) {\n return this._store.getState();\n }\n\n throw new PaymentMethodFailedError('Failed to configure 3DS API.');\n },\n configuration: {\n userLanguage: this._locale,\n wsVersion: 62,\n },\n });\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const { is3dsEnabled } = paymentMethod.config;\n\n if (is3dsEnabled) {\n const newPaymentData = {\n ...paymentData,\n threeDSecure: { token: this._sessionId },\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error) => {\n if (\n !is3dsEnabled ||\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const state = this._store.getState();\n const order = state.order.getOrder();\n const {\n storeProfile: { storeId },\n } = state.config.getStoreConfigOrThrow();\n\n if (!order || !this._sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n const {\n three_ds_result: { token: transactionId },\n } = error.body;\n\n if (!transactionId) {\n return Promise.reject(error);\n }\n\n return this._initiateAuthentication(orderId, transactionId);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._threeDSjs = undefined;\n this._sessionId = '';\n\n return super.deinitialize();\n }\n\n private async _initiateAuthentication(\n orderId: string,\n transactionId: string,\n ): Promise {\n const response: RestApiResponse = await new Promise((resolve, reject) => {\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._threeDSjs.initiateAuthentication(orderId, transactionId, (data) => {\n const error = data.error;\n\n if (error) {\n return reject(new PaymentMethodDeclinedError(error.msg));\n }\n\n if (this._threeDSjs && data.gatewayRecommendation === THREE_D_SECURE_PROCEED) {\n return resolve(data.restApiResponse);\n }\n\n return reject(new PaymentMethodDeclinedError());\n });\n });\n\n if (\n response.transaction &&\n response.transaction.authenticationStatus === THREE_D_SECURE_AVAILABLE\n ) {\n return this._authenticatePayer(orderId, transactionId);\n }\n\n throw new PaymentMethodDeclinedError();\n }\n\n private async _authenticatePayer(\n orderId: string,\n transactionId: string,\n attempt = 1,\n ): Promise {\n return new Promise((_resolve, reject) => {\n if (!this._threeDSjs) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this._threeDSjs.authenticatePayer(\n orderId,\n transactionId,\n async (data) => {\n const error = data.error;\n\n if (error) {\n if (error.cause && error.cause === THREE_D_SECURE_BUSY && attempt < 5) {\n // Wait 3 seconds for MPGS server to process the `initiateAuthentication` call\n // See: Step 1: Initiate Authentication -> Initiate Authentication Request:\n // https://ap-gateway.mastercard.com/api/documentation/integrationGuidelines/supportedFeatures/pickAdditionalFunctionality/authentication/3DS/integrationModelAPI.html?locale=en_US#x_3DSTest\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n return this._authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodDeclinedError());\n }\n\n // ThreeDSjs will handle the redirect so return a promise that doesn't really resolve\n return new Promise(noop);\n },\n { fullScreenRedirect: true },\n );\n });\n }\n}\n","export const THREE_D_SECURE_PROCEED = 'PROCEED';\nexport const THREE_D_SECURE_BUSY = 'SERVER_BUSY';\nexport const THREE_D_SECURE_AVAILABLE = 'AUTHENTICATION_AVAILABLE';\n\nexport interface CBAMPGSHostWindow extends Window {\n ThreeDS?: ThreeDSjs;\n}\n\nexport interface ThreeDSjs {\n // Configuration method for initializing the API.\n configure(config: ThreeDSConfiguration): Promise;\n // Convenience method to check if the API has been configured successfully.\n isConfigured(): boolean;\n // Authentication for the arguments passed.\n initiateAuthentication(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n ): void;\n authenticatePayer(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n optionalParams?: AuthenticatePayerOptionalParams,\n ): void;\n}\n\nexport interface RestApiResponse {\n transaction: {\n authenticationStatus: string;\n };\n}\n\n// Configuration required to configure ThreeDS\nexport interface ThreeDSConfiguration {\n merchantId: string;\n sessionId: string;\n configuration: ThreeDSAPIConfiguration;\n callback(): void;\n}\n\nexport interface ThreeDSAuthenticationResponse {\n error?: ThreeDSAuthenticationError;\n restApiResponse: RestApiResponse;\n gatewayRecommendation: string;\n}\n\nexport interface AuthenticatePayerOptionalParams {\n fullScreenRedirect: boolean;\n}\n\nexport interface ThreeDSAuthenticationError {\n code: string;\n msg: string;\n cause?: string;\n}\n\n// JSON value supporting data elements like userLanguage, REST API version (wsVersion)\nexport interface ThreeDSAPIConfiguration {\n // A language identifier or IETF language tag to control the language of the payment page displayed to the payer.\n // For example, \"en_US\", es, \"fr-CA\". By default, the language is \"en_US\".\n userLanguage: string;\n // The Web Services API version that you submitted the request in. IE: 62\n wsVersion: number;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CBAMPGSHostWindow, ThreeDSjs } from './cba-mpgs';\n\nexport default class CBAMPGSScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CBAMPGSHostWindow = window) {}\n\n async load(testMode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n `//${\n testMode ? 'test' : 'ap'\n }-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`,\n );\n\n if (!this._window.ThreeDS) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.ThreeDS;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class ConvergePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return super.execute(payload, options).catch((error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n });\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport getCallbackUrl from './get-callback-url';\nimport { Masterpass, MasterpassCheckoutOptions } from './masterpass';\nimport MasterpassScriptLoader from './masterpass-script-loader';\n\nexport default class MasterpassPaymentStrategy implements PaymentStrategy {\n private _masterpassClient?: Masterpass;\n private _paymentMethod?: PaymentMethod;\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n\n if (!options.masterpass) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.masterpass\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.masterpass.walletButton &&\n document.getElementById(options.masterpass.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._store.getState();\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._masterpassClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const order = { useStoreCredit: payload.useStoreCredit };\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.gateway\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n // TODO: Refactor the API endpoint to return nonce in the right place.\n const paymentData = this._paymentMethod.initializationData.paymentData;\n\n // TODO: Redirect to Masterpass if nonce has not been generated yet. And then finalise the order when the shopper is redirected back to the checkout page.\n if (!paymentData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"paymentMethod.initializationData.paymentData\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.subtotal.toFixed(2),\n currency: storeConfig.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('checkout'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._masterpassClient) {\n return;\n }\n\n const payload = this._createMasterpassPayload();\n\n this._masterpassClient.checkout(payload);\n }\n}\n","import PaymentMethod from '../../payment-method';\n\nimport { OpyWidgetConfig } from './opy-library';\n\nexport enum ActionTypes {\n FORM_POST = 'FormPost',\n WAIT_FOR_CUSTOMER = 'WaitForCustomer',\n}\n\ninterface FormPost {\n type: ActionTypes.FORM_POST;\n formPost: {\n formPostUrl: string;\n formFields: [\n {\n fieldName: string;\n fieldValue: string;\n },\n ];\n };\n}\n\ninterface WaitForCustomer {\n type: ActionTypes.WAIT_FOR_CUSTOMER;\n}\n\nexport interface OpyPaymentMethod extends PaymentMethod {\n initializationData: {\n nextAction?: FormPost | WaitForCustomer;\n widgetConfig: OpyWidgetConfig;\n };\n}\n\nexport function isOpyPaymentMethod(\n paymentMethod: PaymentMethod,\n): paymentMethod is OpyPaymentMethod {\n return !!paymentMethod.initializationData?.widgetConfig;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum OpyErrorType {\n InvalidCart = 'invalid_cart',\n}\nexport default class OpyError extends StandardError {\n subtype: string;\n\n constructor(subtype: OpyErrorType, displayName: string) {\n super(getErrorMessage(subtype, displayName));\n\n this.name = 'OpyError';\n this.type = 'opy_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: OpyErrorType, displayName: string): string {\n switch (type) {\n case OpyErrorType.InvalidCart:\n return `Cart price is different to ${displayName} plan amount.`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { StorefrontPaymentRequestSender } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { ActionTypes, isOpyPaymentMethod } from './opy';\nimport { OpyWidgetConfig } from './opy-library';\nimport OpyError, { OpyErrorType } from './opy-payment-error';\nimport OpyScriptLoader from './opy-script-loader';\n\nexport default class OpyPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: OpyScriptLoader,\n ) {}\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (options?.opy?.containerId) {\n const {\n methodId,\n opy: { containerId },\n } = options;\n\n const paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod && isOpyPaymentMethod(paymentMethod)) {\n const {\n initializationData: { widgetConfig },\n } = paymentMethod;\n\n await this._installWidget(containerId, widgetConfig);\n }\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (!isOpyPaymentMethod(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken: nonce,\n initializationData: { nextAction },\n } = paymentMethod;\n\n if (!nextAction) {\n const { displayName = 'Openpay' } = paymentMethod.config;\n\n throw new OpyError(OpyErrorType.InvalidCart, displayName);\n }\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._storefrontPaymentRequestSender.saveExternalId(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (nextAction.type === ActionTypes.FORM_POST) {\n const { formPostUrl, formFields } = nextAction.formPost;\n\n const url = new URL(formPostUrl.replace(/\\/$/, ''));\n\n formFields.forEach(({ fieldName, fieldValue }) => {\n url.searchParams.append(fieldName, fieldValue);\n });\n\n return new Promise(() => window.location.assign(decodeURI(url.href)));\n }\n\n throw new NotImplementedError(`Unsupported action type: ${nextAction.type}`);\n }\n\n throw error;\n }\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private async _installWidget(containerId: string, config: OpyWidgetConfig): Promise {\n const widgetContainer = document.getElementById(containerId);\n\n if (widgetContainer) {\n try {\n const widget = await this._scriptLoader.loadOpyWidget(config.region);\n\n widget.Config(config);\n } catch (error) {\n return;\n }\n\n widgetContainer.appendChild(document.createElement('opy-learn-more-button'));\n }\n }\n}\n","export enum OpyRegion {\n AU = 'AU',\n UK = 'UK',\n US = 'US',\n}\n\n/**\n * https://widgets.openpay.com.au/config\n */\nexport interface OpyWidgetConfig {\n /**\n * The region your store is located in.\n */\n region: OpyRegion;\n /**\n * The currency symbol used in the widgets.\n */\n currency: '$' | '£';\n /**\n * An array of available plan tiers you have available in months.\n */\n planTiers: number[];\n /**\n * The minimum eligible amount required before Opy is eligible.\n */\n minEligibleAmount: number;\n /**\n * The maximum eligible amount required before Opy is eligible.\n */\n maxEligibleAmount: number;\n /**\n * Type of your store.\n */\n type: 'Online';\n}\n\nexport interface OpyWidget {\n /**\n * Initialize the library.\n *\n * @param config Properties with the correct purchase limits, plan tiers, etc.\n */\n Config(config: OpyWidgetConfig): void;\n}\n\nexport interface OpyHostWindow extends Window {\n /**\n * The Opy widgets library.\n */\n OpenpayWidgets?: OpyWidget;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { OpyHostWindow, OpyRegion, OpyWidget } from './opy-library';\n\nconst AU_REGION_URL = 'https://widgets.openpay.com.au/lib/openpay-widgets.min.js';\n\nconst SOURCES = {\n AU: AU_REGION_URL,\n UK: AU_REGION_URL,\n US: 'https://widgets.opy.com/lib/openpay-widgets.min.js',\n};\n\nexport default class OpyScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: OpyHostWindow = window) {}\n\n async loadOpyWidget(region = OpyRegion.AU): Promise {\n await this._scriptLoader.loadScript(SOURCES[region]);\n\n if (!this._window.OpenpayWidgets) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.OpenpayWidgets;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport PaypalScriptLoader from './paypal-script-loader';\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private _paypalSdk?: PaypalSDK;\n private _paymentMethod?: PaymentMethod;\n private _useRedirectFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _scriptLoader: PaypalScriptLoader,\n private _window: PaypalHostWindow = window,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n this._useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n if (!this._isInContextEnabled()) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._scriptLoader\n .loadPaypal()\n .then((paypal) => {\n this._paypalSdk = paypal;\n\n if (!this._paymentMethod || !this._paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._paypalSdk.checkout.setup(this._paymentMethod.config.merchantId, {\n button: 'paypal-button',\n environment: this._paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._isInContextEnabled() && this._paypalSdk) {\n this._paypalSdk.checkout.closeFlow();\n this._paypalSdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const paypal = this._paypalSdk;\n\n if (this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n }\n\n if (!this._isInContextEnabled() || this._useRedirectFlow) {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl && this._window.top) {\n this._window.top.location.href = redirectUrl;\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n });\n }\n\n if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n paypal.checkout.startFlow(redirectUrl);\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n })\n .catch((error) => {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _isAcknowledgedOrFinalized(): boolean {\n const state = this._store.getState();\n\n return (\n state.payment.getPaymentStatus() === paymentStatusTypes.ACKNOWLEDGE ||\n state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE\n );\n }\n\n private _isInContextEnabled(): boolean {\n return !!(this._paymentMethod && this._paymentMethod.config.merchantId);\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalScriptLoader {\n private _window: PaypalHostWindow;\n\n constructor(private _scriptLoader: ScriptLoader) {\n this._window = window;\n }\n\n async loadPaypal(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n };\n\n merchantId\n ? await this._scriptLoader.loadScript(scriptSrc, options)\n : await this._scriptLoader.loadScript(scriptSrc);\n\n if (!this._window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.paypal;\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"query-string\");","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\n}\n","import { exclude, ParsedUrl, parseUrl, stringifyUrl } from 'query-string';\n\nexport const PENDING_REDIRECT_PARAM = 'redirecting';\n\nexport class RedirectionState {\n private _isRedirecting: boolean;\n\n constructor() {\n this._isRedirecting = this.currentUrlHasRedirectingParam();\n }\n\n isRedirecting() {\n return this._isRedirecting;\n }\n\n setRedirecting(value: boolean) {\n if (value) {\n this.setRedirectingParamOnUrl();\n } else {\n this.removeRedirectingParamFromUrl();\n }\n\n this._isRedirecting = value;\n }\n\n private currentUrlHasRedirectingParam(): boolean {\n return PENDING_REDIRECT_PARAM in this.getCurrentUrl().query;\n }\n\n private getCurrentUrl(): ParsedUrl {\n return parseUrl(window.location.href);\n }\n\n private replaceCurrentUrl(url: string) {\n window.history.replaceState(null, '', url);\n }\n\n private setRedirectingParamOnUrl() {\n if (this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n const currentUrl = this.getCurrentUrl();\n const updatedUrl = {\n ...currentUrl,\n query: {\n ...currentUrl.query,\n [PENDING_REDIRECT_PARAM]: 'true',\n },\n };\n\n this.replaceCurrentUrl(stringifyUrl(updatedUrl));\n }\n\n private removeRedirectingParamFromUrl() {\n if (!this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n this.replaceCurrentUrl(exclude(window.location.href, [PENDING_REDIRECT_PARAM]));\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { overSome } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\nimport {\n handleHumanVerification,\n HumanVerification,\n isHumanVerification,\n} from './human-verification';\nimport { handleRedirect, isRedirect, Redirect } from './redirect';\n\nexport type Continue = Redirect | HumanVerification;\n\nconst isAnyContinue = overSome([isRedirect, isHumanVerification]);\n\nexport const isContinue = (body: PaymentsAPIResponse['body']): body is Continue =>\n isAnyContinue(body);\n\nexport interface ContinueCallbacks {\n humanVerification?(additionalAction: PaymentAdditionalAction): Promise;\n}\n\nexport class ContinueHandler {\n constructor(\n private _formPoster: FormPoster,\n private _humanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n handle(body: Continue, callbacks?: ContinueCallbacks): Promise {\n switch (body.code) {\n case 'redirect':\n return handleRedirect(body.parameters, this._formPoster);\n\n case 'resubmit_with_human_verification':\n return handleHumanVerification(\n body.parameters,\n this._humanVerificationHandler,\n callbacks?.humanVerification,\n );\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { get, isObject, isString, isUndefined, noop } from 'lodash';\n\nimport { PaymentMethodCancelledError } from '../../../../../errors';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\nimport { RedirectionState } from './RedirectionState';\n\ninterface Parameters {\n url: string;\n form_fields?: Record;\n}\n\nexport interface Redirect {\n type: 'continue';\n code: 'redirect';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const formFields = get(x, 'form_fields');\n\n return isString(get(x, 'url')) && (isUndefined(formFields) || isObject(formFields));\n};\n\nexport const isRedirect = (body: PaymentsAPIResponse['body']): body is Redirect =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'redirect' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleRedirect = (\n { url, form_fields }: Parameters,\n formPoster: FormPoster,\n): Promise => {\n const redirectionState = new RedirectionState();\n\n if (redirectionState.isRedirecting()) {\n redirectionState.setRedirecting(false);\n\n return Promise.reject(new PaymentMethodCancelledError());\n }\n\n redirectionState.setRedirecting(true);\n\n if (form_fields) {\n formPoster.postForm(url, form_fields);\n } else {\n window.location.assign(url);\n }\n\n return new Promise(noop);\n};\n","import { get, isArray } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\ninterface VerificationMethod {\n id: string;\n parameters: Record;\n}\n\ninterface Parameters {\n available_methods: VerificationMethod[];\n}\n\nexport interface HumanVerification {\n type: 'continue';\n code: 'resubmit_with_human_verification';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const availableMethods = get(x, 'available_methods');\n\n return isArray(availableMethods);\n};\n\nexport const isHumanVerification = (body: PaymentsAPIResponse['body']): body is HumanVerification =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'resubmit_with_human_verification' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleHumanVerification = async (\n { available_methods }: Parameters,\n humanVerificationHandler?: PaymentHumanVerificationHandler,\n callback?: (additionalAction: PaymentAdditionalAction) => Promise,\n): Promise => {\n if (!callback) {\n throw new Error('PPSDK human verification callback function is missing.');\n }\n\n if (!humanVerificationHandler) {\n throw new Error('PPSDK human verification handler is missing.');\n }\n\n if (available_methods.length === 0) {\n throw Error('Human verification method is missing.');\n }\n\n // Only one method is expected because google recaptcha only is supported\n const { id, parameters } = available_methods[0];\n\n const additionalAction: PaymentAdditionalAction = await humanVerificationHandler.handle(\n id,\n parameters.key,\n );\n\n return callback(additionalAction);\n};\n","import { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nimport { ContinueCallbacks, ContinueHandler, isContinue } from './continue-handler';\nimport { handleError, isError } from './error';\nimport { handleFailure, isFailure } from './failure';\nimport { handleSuccess, isSuccess } from './success';\nimport { handleUnsupported } from './unsupported';\n\ninterface StepHandlerCallbacks {\n continue?: ContinueCallbacks;\n}\n\nexport class StepHandler {\n constructor(private _continueHandler: ContinueHandler) {}\n\n handle(response: PaymentsAPIResponse, callbacks?: StepHandlerCallbacks): Promise {\n const { body } = response;\n\n if (isSuccess(body)) {\n return handleSuccess();\n }\n\n if (isContinue(body)) {\n return this._continueHandler.handle(body, callbacks?.continue);\n }\n\n if (isFailure(response)) {\n return handleFailure(response);\n }\n\n if (isError(response)) {\n return handleError(response);\n }\n\n return handleUnsupported(response);\n }\n}\n","import { get } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface Success {\n type: 'success';\n}\n\nexport const isSuccess = (body: PaymentsAPIResponse['body']): body is Success =>\n get(body, 'type') === 'success';\n\nexport const handleSuccess = () => Promise.resolve();\n","import { get, isString } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface FailureResponse extends PaymentsAPIResponse {\n body: {\n type: 'failure';\n code: string;\n };\n}\n\nexport const isFailure = (response: PaymentsAPIResponse): response is FailureResponse =>\n get(response.body, 'type') === 'failure' && isString(get(response.body, 'code'));\n\nconst toRequestErrorFormat = (failureResponse: FailureResponse) => ({\n ...failureResponse,\n body: {\n errors: [{ code: failureResponse.body.code }],\n },\n});\n\nexport const handleFailure = (response: FailureResponse): Promise =>\n Promise.reject(new RequestError(toRequestErrorFormat(response)));\n","import { get } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface ErrorResponse extends PaymentsAPIResponse {\n body: {\n type: 'error';\n };\n}\n\nexport const isError = (response: PaymentsAPIResponse): response is ErrorResponse =>\n get(response.body, 'type') === 'error';\n\nexport const handleError = (response: ErrorResponse) => Promise.reject(new RequestError(response));\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentHumanVerificationHandler } from '../../../../spam-protection';\n\nimport { ContinueHandler } from './continue-handler';\nimport { StepHandler } from './step-handler';\n\nexport const createStepHandler = (\n formPoster: FormPoster,\n humanVerificationHandler: PaymentHumanVerificationHandler,\n) => new StepHandler(new ContinueHandler(formPoster, humanVerificationHandler));\n","import { BrowserStorage } from '../../../common/storage';\n\ntype CompletedPayments = string[];\n\nconst COMPLETED_PAYMENTS_KEY = 'completed-payments';\n\nexport class PPSDKCompletedPayments {\n constructor(private _browserStorage: BrowserStorage) {}\n\n isCompleted(paymentId: string): boolean {\n return this.getCompletedPayments().indexOf(paymentId) >= 0;\n }\n\n setCompleted(paymentId: string): void {\n const completedPayments = this.getCompletedPayments();\n\n completedPayments.push(paymentId);\n\n this.setCompletedPayments(completedPayments);\n }\n\n private getCompletedPayments(): CompletedPayments {\n return this._browserStorage.getItem(COMPLETED_PAYMENTS_KEY) || [];\n }\n\n private setCompletedPayments(completedPayments: CompletedPayments): void {\n this._browserStorage.setItem(COMPLETED_PAYMENTS_KEY, completedPayments);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { BrowserStorage } from '../../../common/storage';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { getPPSDKMethod } from './get-ppsdk-payment-method';\nimport { PPSDKCompletedPayments } from './ppsdk-completed-payments';\nimport { PaymentResumer } from './ppsdk-payment-resumer';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\n\nexport class PPSDKStrategy implements PaymentStrategy {\n private _subStrategy?: SubStrategy;\n private _completedPayments: PPSDKCompletedPayments;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _subStrategyRegistry: SubStrategyRegistry,\n private _paymentResumer: PaymentResumer,\n browserStorage: BrowserStorage,\n ) {\n this._completedPayments = new PPSDKCompletedPayments(browserStorage);\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n const { payment, ...order } = payload;\n const { _subStrategy: subStrategy } = this;\n\n if (!subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const token = this._store.getState().order.getOrderMeta()?.token;\n\n if (!token) {\n throw new MissingDataError(MissingDataErrorType.MissingOrder);\n }\n\n await subStrategy.execute({ methodId, payment, bigpayBaseUrl, token });\n\n return this._store.getState();\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const order = this._store.getState().order.getOrderOrThrow();\n\n if (order.isComplete) {\n return this._store.getState();\n }\n\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentId = this._store.getState().order.getPaymentId(options.methodId);\n\n if (!paymentId || !order || this._completedPayments.isCompleted(paymentId)) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const { orderId } = order;\n\n await this._paymentResumer.resume({ paymentId, bigpayBaseUrl, orderId }).catch((error) => {\n this._completedPayments.setCompleted(paymentId);\n throw error;\n });\n\n return this._store.getState();\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n if (!paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._subStrategy = this._subStrategyRegistry.getByMethod(paymentMethod);\n\n if (!this._subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._subStrategy.initialize(options);\n\n return this._store.getState();\n }\n\n async deinitialize(_options?: PaymentRequestOptions): Promise {\n this._subStrategy?.deinitialize();\n\n return this._store.getState();\n }\n}\n","import { CheckoutStore } from '../../../checkout';\nimport { isPPSDKPaymentMethod, PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\ntype GetPPSDKMethod = (store: CheckoutStore, methodId: string) => PPSDKPaymentMethod | undefined;\n\nexport const getPPSDKMethod: GetPPSDKMethod = (store, methodId) => {\n const paymentMethod = store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !isPPSDKPaymentMethod(paymentMethod)) {\n return;\n }\n\n return paymentMethod;\n};\n","import { cond, constant, stubTrue } from 'lodash';\n\nimport { Registry } from '../../../common/registry';\nimport { PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\nimport { isCard, isNone } from './initialization-strategies';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\n\nconst getToken = cond([\n [isCard, constant(SubStrategyType.CARD)],\n [isNone, constant(SubStrategyType.NONE)],\n [stubTrue, constant(SubStrategyType.UNSUPPORTED)],\n]);\n\nexport class SubStrategyRegistry extends Registry {\n getByMethod(paymentMethod: PPSDKPaymentMethod): SubStrategy | undefined {\n const token = getToken(paymentMethod.initializationStrategy);\n\n return this.get(token);\n }\n}\n","import { InitializationStrategy } from '../../../';\n\ninterface Card {\n type: 'card_ui';\n}\n\nexport const isCard = (strategy: Pick): strategy is Card =>\n strategy.type === 'card_ui';\n","import { InitializationStrategy } from '../../../';\n\ninterface None {\n type: 'none';\n}\n\nexport const isNone = (strategy: Pick): strategy is None =>\n strategy.type === 'none';\n","import { CheckoutStore } from '../../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../../hosted-form';\nimport { OrderActionCreator } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport PaymentAdditionalAction from '../../../payment-additional-action';\nimport { PaymentInitializeOptions } from '../../../payment-request-options';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class CardSubStrategy implements SubStrategy {\n protected _hostedForm?: HostedForm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _ppsdkStepHandler: StepHandler,\n ) {}\n\n async execute(settings: SubStrategySettings): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { additionalAction, payment } = settings;\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await form.validate();\n\n const { payload } = await form.submit(payment, additionalAction);\n\n const { response } = payload;\n\n const humanVerificationCallback = async (\n additionalAction: PaymentAdditionalAction,\n ): Promise => this.execute({ additionalAction, ...settings });\n\n await this._ppsdkStepHandler.handle(response, {\n continue: {\n humanVerification: humanVerificationCallback,\n },\n });\n\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions);\n\n await form.attach();\n\n this._hostedForm = form;\n }\n\n deinitialize(): void {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class NoneSubStrategy implements SubStrategy {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n execute({ methodId, bigpayBaseUrl, token }: SubStrategySettings): Promise {\n const body = { payment_method_id: methodId };\n const options = {\n credentials: false,\n body,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .post(`${bigpayBaseUrl}/payments`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): void {}\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator } from '../../../order';\n\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\nimport { StepHandler } from './step-handler';\nimport { CardSubStrategy, NoneSubStrategy } from './sub-strategies';\n\nexport const createSubStrategyRegistry = (\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n requestSender: RequestSender,\n stepHandler: StepHandler,\n hostedFormFactory: HostedFormFactory,\n) => {\n const registry = new SubStrategyRegistry();\n\n registry.register(\n SubStrategyType.CARD,\n () => new CardSubStrategy(store, orderActionCreator, hostedFormFactory, stepHandler),\n );\n\n registry.register(SubStrategyType.NONE, () => new NoneSubStrategy(requestSender, stepHandler));\n\n registry.register(SubStrategyType.UNSUPPORTED, () => undefined);\n\n return registry;\n};\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\n\nimport { PaymentsAPIResponse } from './ppsdk-payments-api-response';\nimport { StepHandler } from './step-handler';\n\ninterface ResumeSettings {\n orderId: number;\n paymentId: string;\n bigpayBaseUrl: string;\n}\n\nexport class PaymentResumer {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n async resume({ paymentId, bigpayBaseUrl, orderId }: ResumeSettings): Promise {\n const token = await this._getToken(orderId).catch(() => {\n throw new OrderFinalizationNotRequiredError();\n });\n\n const options = {\n credentials: false,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .get(`${bigpayBaseUrl}/payments/${paymentId}`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n private async _getToken(orderId: number): Promise {\n const url = `/api/storefront/payments/auth-token`;\n const options = {\n params: {\n order_id: orderId,\n },\n };\n\n return this._requestSender\n .get<{ auth_token: string }>(url, options)\n .then(({ body }) => body.auth_token);\n }\n}\n","import { merge } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport WepayRiskClient from './wepay-risk-client';\n\nexport default class WepayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n void this._wepayRiskClient.initialize();\n\n return super.initialize(options);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const token = this._wepayRiskClient.getRiskToken();\n const payloadWithToken = merge({}, payload, {\n payment: {\n paymentData: {\n deviceSessionId: token,\n },\n },\n });\n\n return super.execute(payloadWithToken, options);\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport WepayRisk from './wepay-risk';\nimport WepayWindow from './wepay-window';\n\nconst SCRIPT_SRC = '//static.wepay.com/min/js/risk.1.latest.js';\n\nexport default class WepayRiskClient {\n private _riskClient?: WepayRisk;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n initialize(): Promise {\n return this._scriptLoader\n .loadScript(SCRIPT_SRC)\n .then(() => (this._riskClient = (window as unknown as WepayWindow).WePay.risk))\n .then(() => this);\n }\n\n getRiskToken(): string {\n if (!this._riskClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._riskClient.generate_risk_token();\n\n return this._riskClient.get_risk_token();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody } from './instrument-response-body';\n\nexport enum InstrumentActionType {\n LoadInstrumentsRequested = 'LOAD_INSTRUMENTS_REQUESTED',\n LoadInstrumentsSucceeded = 'LOAD_INSTRUMENTS_SUCCEEDED',\n LoadInstrumentsFailed = 'LOAD_INSTRUMENTS_FAILED',\n\n DeleteInstrumentRequested = 'DELETE_INSTRUMENT_REQUESTED',\n DeleteInstrumentSucceeded = 'DELETE_INSTRUMENT_SUCCEEDED',\n DeleteInstrumentFailed = 'DELETE_INSTRUMENT_FAILED',\n}\n\nexport type InstrumentAction = LoadInstrumentsAction | DeleteInstrumentAction;\n\nexport type LoadInstrumentsAction =\n | LoadInstrumentsRequestedAction\n | LoadInstrumentsSucceededAction\n | LoadInstrumentsFailedAction;\n\nexport type DeleteInstrumentAction =\n | DeleteInstrumentRequestedAction\n | DeleteInstrumentSucceededAction\n | DeleteInstrumentFailedAction;\n\nexport interface LoadInstrumentsRequestedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsRequested;\n}\n\nexport interface LoadInstrumentsSucceededAction\n extends Action {\n type: InstrumentActionType.LoadInstrumentsSucceeded;\n}\n\nexport interface LoadInstrumentsFailedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsFailed;\n}\n\nexport interface DeleteInstrumentRequestedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentRequested;\n}\n\nexport interface DeleteInstrumentSucceededAction\n extends Action {\n type: InstrumentActionType.DeleteInstrumentSucceeded;\n}\n\nexport interface DeleteInstrumentFailedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { Address } from '../../address';\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../../checkout';\nimport { addMinutes, isFuture } from '../../common/date-time';\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\n\nimport { SessionContext, VaultAccessToken } from './instrument';\nimport {\n DeleteInstrumentAction,\n InstrumentActionType,\n LoadInstrumentsAction,\n} from './instrument-actions';\nimport InstrumentRequestSender from './instrument-request-sender';\n\nexport default class InstrumentActionCreator {\n constructor(private _instrumentRequestSender: InstrumentRequestSender) {}\n\n loadInstruments(): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(InstrumentActionType.LoadInstrumentsRequested));\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n const shippingAddress = this._getShippingAddress(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .loadInstruments(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n shippingAddress,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.LoadInstrumentsSucceeded,\n body,\n currentToken,\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(InstrumentActionType.LoadInstrumentsFailed, response),\n );\n });\n });\n }\n\n deleteInstrument(\n instrumentId: string,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(\n createAction(InstrumentActionType.DeleteInstrumentRequested, undefined, {\n instrumentId,\n }),\n );\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .deleteInstrument(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n instrumentId,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.DeleteInstrumentSucceeded,\n body,\n {\n instrumentId,\n ...currentToken,\n },\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(\n InstrumentActionType.DeleteInstrumentFailed,\n response,\n { instrumentId },\n ),\n );\n });\n });\n }\n\n private _isValidVaultAccessToken(token: VaultAccessToken): boolean {\n if (!token || !token.vaultAccessToken) {\n return false;\n }\n\n const expiryBuffer = 2;\n const expiry = addMinutes(new Date(token.vaultAccessExpiry), expiryBuffer);\n\n return isFuture(expiry);\n }\n\n private _getCurrentAccessToken(store: ReadableCheckoutStore): VaultAccessToken | undefined {\n const { instruments } = store.getState();\n const meta = instruments.getInstrumentsMeta();\n\n if (!meta) {\n return;\n }\n\n return {\n vaultAccessToken: meta.vaultAccessToken,\n vaultAccessExpiry: meta.vaultAccessExpiry,\n };\n }\n\n private _getValidAccessToken(token?: VaultAccessToken): Promise {\n return token && this._isValidVaultAccessToken(token)\n ? Promise.resolve(token)\n : this._instrumentRequestSender.getVaultAccessToken().then(({ body }) => body);\n }\n\n private _getShippingAddress(store: ReadableCheckoutStore): Address | Address[] | undefined {\n const state = store.getState();\n const addresses = state.shippingAddress.getShippingAddresses();\n\n return addresses.length > 1 ? addresses : state.shippingAddress.getShippingAddress();\n }\n\n private _getSessionContext(store: ReadableCheckoutStore): SessionContext {\n const state = store.getState();\n const config = state.config.getStoreConfig();\n const cart = state.cart.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { customerId } = cart;\n const { storeId } = config.storeProfile;\n const { code } = config.shopperCurrency.isTransactional\n ? config.shopperCurrency\n : config.currency;\n\n return {\n customerId,\n storeId,\n currencyCode: code,\n };\n }\n}\n","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\n}\n","export default function addMinutes(date: Date, amount: number): Date {\n const newDate = new Date(date.getTime());\n\n newDate.setMinutes(date.getMinutes() + amount);\n\n return newDate;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentResponse from '../payment-response';\n\nimport PaymentInstrument, { VaultAccessToken } from './instrument';\nimport {\n BankInternalInstrument,\n InstrumentErrorResponseBody,\n InstrumentsResponseBody,\n InternalInstrument,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n PayPalInternalInstrument,\n} from './instrument-response-body';\nimport { mapToBankInstrument } from './map-to-bank-instrument';\nimport { mapToCardInstrument } from './map-to-card-instrument';\nimport { mapToPayPalInstrument } from './map-to-paypal-instrument';\n\nexport default class InstrumentResponseTransformer {\n transformResponse(\n response: PaymentResponse,\n ): Response {\n const { body, ...payload } = this._transformResponse(response);\n\n return {\n ...payload,\n body: {\n vaultedInstruments: this._transformVaultedInstruments(body.vaulted_instruments),\n },\n };\n }\n\n transformErrorResponse(\n response: PaymentResponse,\n ): Response {\n return this._transformResponse(response);\n }\n\n transformVaultAccessResponse(\n response: Response,\n ): Response {\n return {\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n };\n }\n\n private _transformVaultedInstruments(\n vaultedInstruments: InternalInstrument[] = [],\n ): PaymentInstrument[] {\n return vaultedInstruments.map((instrument) => {\n if (this._isPayPalInstrument(instrument)) {\n return mapToPayPalInstrument(instrument);\n }\n\n if (this._isBankInstrument(instrument)) {\n return mapToBankInstrument(instrument);\n }\n\n return mapToCardInstrument(instrument);\n });\n }\n\n private _isPayPalInstrument(\n instrument: InternalInstrument,\n ): instrument is PayPalInternalInstrument {\n return instrument.method_type === 'paypal';\n }\n\n private _isBankInstrument(\n instrument: InternalInstrument,\n ): instrument is BankInternalInstrument {\n return instrument.method_type === 'bank';\n }\n\n private _transformResponse(response: PaymentResponse): Response {\n const { data: body, ...payload } = response;\n\n return {\n ...payload,\n body,\n };\n }\n}\n","import { PayPalInstrument } from './instrument';\nimport { PayPalInternalInstrument } from './instrument-response-body';\n\nexport function mapToPayPalInstrument(instrument: PayPalInternalInstrument): PayPalInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n externalId: instrument.external_id,\n trustedShippingAddress: instrument.trusted_shipping_address,\n method: 'paypal',\n type: 'account',\n };\n}\n","import { BankInstrument } from './instrument';\nimport { BankInternalInstrument } from './instrument-response-body';\n\nexport function mapToBankInstrument(instrument: BankInternalInstrument): BankInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n trustedShippingAddress: instrument.trusted_shipping_address,\n accountNumber: instrument.account_number,\n issuer: instrument.issuer,\n iban: instrument.iban,\n method: instrument.method,\n type: 'bank',\n };\n}\n","import { CardInstrument } from './instrument';\nimport { CardInternalInstrument } from './instrument-response-body';\n\nexport function mapToCardInstrument(instrument: CardInternalInstrument): CardInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n iin: instrument.iin,\n last4: instrument.last_4,\n expiryMonth: instrument.expiry_month,\n expiryYear: instrument.expiry_year,\n brand: instrument.brand,\n trustedShippingAddress: instrument.trusted_shipping_address,\n untrustedShippingCardVerificationMode:\n instrument.untrusted_shipping_address_card_verification_mode,\n method: instrument.method,\n type: 'card',\n };\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Address, mapToInternalAddress } from '../../address';\nimport { RequestOptions } from '../../common/http-request';\nimport PaymentResponse from '../payment-response';\n\nimport { InstrumentRequestContext, VaultAccessToken } from './instrument';\nimport {\n InstrumentsResponseBody,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n} from './instrument-response-body';\nimport InstrumentResponseTransformer from './instrument-response-transformer';\n\nexport default class InstrumentRequestSender {\n private _transformer: InstrumentResponseTransformer;\n\n constructor(private _client: any, private _requestSender: RequestSender) {\n this._transformer = new InstrumentResponseTransformer();\n }\n\n getVaultAccessToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/checkout/payments/vault-access-token';\n\n return this._requestSender\n .get(url, { timeout })\n .then((response) => ({\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n }));\n }\n\n loadInstruments(\n requestContext: InstrumentRequestContext,\n shippingAddress?: Address | Address[],\n ): Promise> {\n return shippingAddress\n ? this._loadInstrumentsWithAddress(requestContext, shippingAddress)\n : this._loadInstruments(requestContext);\n }\n\n deleteInstrument(\n requestContext: InstrumentRequestContext,\n instrumentId: string,\n ): Promise> {\n const payload = {\n ...requestContext,\n instrumentId,\n };\n\n return new Promise((resolve, reject) => {\n this._client.deleteShopperInstrument(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstruments(\n requestContext: InstrumentRequestContext,\n ): Promise> {\n return new Promise((resolve, reject) => {\n this._client.loadInstruments(\n requestContext,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstrumentsWithAddress(\n requestContext: InstrumentRequestContext,\n shippingAddress: Address | Address[],\n ): Promise> {\n const payload = {\n ...requestContext,\n shippingAddress: Array.isArray(shippingAddress)\n ? shippingAddress.map((address) => mapToInternalAddress(address))\n : mapToInternalAddress(shippingAddress),\n };\n\n return new Promise((resolve, reject) => {\n this._client.loadInstrumentsWithAddress(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { PickupOptionMeta, PickupOptionResult } from './pickup-option';\n\nexport enum PickupOptionActionType {\n LoadPickupOptionsRequested = 'LOAD_PICKUP_OPTIONS_REQUESTED',\n LoadPickupOptionsSucceeded = 'LOAD_PICKUP_OPTIONS_SUCCEEDED',\n LoadPickupOptionsFailed = 'LOAD_PICKUP_OPTIONS_FAILED',\n}\n\nexport type LoadPickupOptionsAction =\n | PickupOptionRequestedAction\n | LoadPickupOptionsSucceededAction\n | LoadPickupOptionsFailedAction;\n\nexport interface PickupOptionRequestedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsRequested;\n}\n\nexport interface LoadPickupOptionsSucceededAction\n extends Action {\n type: PickupOptionActionType.LoadPickupOptionsSucceeded;\n}\n\nexport interface LoadPickupOptionsFailedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsFailed;\n}\n","import {\n createAction,\n createErrorAction,\n ReadableDataStore,\n ThunkAction,\n} from '@bigcommerce/data-store';\nimport { includes } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { LineItem } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { PickupOptionAPIRequestBody, PickupOptionRequestBody } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionRequestSender from './pickup-option-request-sender';\n\nexport default class PickupOptionActionCreator {\n constructor(private _pickupOptionRequestSender: PickupOptionRequestSender) {}\n\n loadPickupOptions(\n query: PickupOptionRequestBody,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const apiQuery = this._hydrateApiQuery(store, query);\n\n observer.next(createAction(PickupOptionActionType.LoadPickupOptionsRequested));\n\n this._pickupOptionRequestSender\n .fetchPickupOptions(apiQuery)\n .then((response) => {\n observer.next(\n createAction(\n PickupOptionActionType.LoadPickupOptionsSucceeded,\n response.body.results,\n query,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PickupOptionActionType.LoadPickupOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _hydrateApiQuery(\n store: ReadableDataStore,\n query: PickupOptionRequestBody,\n ): PickupOptionAPIRequestBody {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const consignment = state.consignments.getConsignmentById(query.consignmentId);\n\n if (!consignment) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentLineItems = consignment.lineItemIds;\n const physicalItems = cart.lineItems.physicalItems;\n const cartItems = physicalItems\n .filter((item: LineItem) => includes(consignmentLineItems, item.id))\n .map((item) => ({\n variantId: item.variantId,\n quantity: item.quantity,\n }));\n\n return {\n searchArea: query.searchArea,\n items: cartItems,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { PickupOptionAPIRequestBody, PickupOptionResponse } from './pickup-option';\n\nconst url = '/api/storefront/pickup-options';\n\nexport default class PickupOptionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n fetchPickupOptions(query: PickupOptionAPIRequestBody): Promise> {\n return this._requestSender.post(url, {\n headers: { Accept: ContentType.Json, ...SDK_VERSION_HEADERS },\n body: query,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ShippingStrategyActionType {\n UpdateAddressFailed = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED',\n UpdateAddressRequested = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED',\n UpdateAddressSucceeded = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED',\n SelectOptionFailed = 'SHIPPING_STRATEGY_SELECT_OPTION_FAILED',\n SelectOptionRequested = 'SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED',\n SelectOptionSucceeded = 'SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED',\n InitializeFailed = 'SHIPPING_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'SHIPPING_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'SHIPPING_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type ShippingStrategyAction =\n | ShippingStrategyUpdateAddressAction\n | ShippingStrategySelectOptionAction\n | ShippingStrategyInitializeAction\n | ShippingStrategyDeinitializeAction\n | ShippingStrategyWidgetAction;\n\nexport type ShippingStrategyUpdateAddressAction =\n | UpdateAddressRequestedAction\n | UpdateAddressSucceededAction\n | UpdateAddressFailedAction;\n\nexport type ShippingStrategySelectOptionAction =\n | SelectOptionRequestedAction\n | SelectOptionSucceededAction\n | SelectOptionFailedAction;\n\nexport type ShippingStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type ShippingStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type ShippingStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface UpdateAddressRequestedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressRequested;\n}\n\nexport interface UpdateAddressSucceededAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressSucceeded;\n}\n\nexport interface UpdateAddressFailedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressFailed;\n}\n\nexport interface SelectOptionRequestedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionRequested;\n}\n\nexport interface SelectOptionSucceededAction extends Action {\n type: ShippingStrategyActionType.SelectOptionSucceeded;\n}\n\nexport interface SelectOptionFailedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: ShippingStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport { ShippingInitializeOptions, ShippingRequestOptions } from './shipping-request-options';\nimport {\n ShippingStrategyAction,\n ShippingStrategyActionType,\n ShippingStrategyDeinitializeAction,\n ShippingStrategyInitializeAction,\n ShippingStrategySelectOptionAction,\n ShippingStrategyUpdateAddressAction,\n} from './shipping-strategy-actions';\nimport { ShippingStrategy } from './strategies';\n\nexport default class ShippingStrategyActionCreator {\n constructor(private _strategyRegistry: Registry) {}\n\n updateAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .updateAddress(address, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.UpdateAddressSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.UpdateAddressFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n selectOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.SelectOptionRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .selectOption(shippingOptionId, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.SelectOptionSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.SelectOptionFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n initialize(\n options?: ShippingInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n const mergedOptions = { ...options, methodId };\n\n if (methodId && state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.InitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .initialize(mergedOptions)\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.InitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(ShippingStrategyActionType.InitializeFailed, error, {\n methodId,\n }),\n );\n });\n });\n }\n\n deinitialize(\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n if (methodId && !state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .deinitialize({ ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.DeinitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.DeinitializeFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: ShippingRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(ShippingStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this._window.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this._window, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n getElements(stripeClient: StripeUPEClient, options: StripeElementsOptions): StripeElements {\n let stripeElements = this._window.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this._window, { bcStripeElements: stripeElements });\n } else {\n stripeElements.fetchUpdates();\n stripeElements.update(options);\n }\n\n return stripeElements;\n }\n\n private async load() {\n await this._scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe;\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2PaymentProcessor,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\n\nimport { ConsignmentActionCreator, ShippingStrategyActionCreator } from '../..';\nimport { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class AmazonPayV2ShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n const updateAddressRequestBody = {\n ...shippingAddress,\n customFields: address.customFields,\n };\n\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options),\n );\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { amazonpay, methodId } = options;\n\n if (!amazonpay || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.amazonpay\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n const { paymentToken, region } = paymentMethod.initializationData;\n const buttonId = amazonpay.editAddressButtonId;\n\n if (paymentToken && buttonId) {\n const shouldShowLoadingSpinner = this._shouldShowLoadingSpinner(region);\n\n this._bindEditButton(buttonId, paymentToken, 'changeAddress', shouldShowLoadingSpinner);\n }\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _bindEditButton(\n id: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n shouldShowLoadingSpinner: boolean,\n ): void {\n const button = document.getElementById(id);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (shouldShowLoadingSpinner) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._shippingStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _shouldShowLoadingSpinner(region: string) {\n return region !== 'us';\n }\n}\n","type PaymentInstrument = CardInstrument | AccountInstrument;\n\nexport default PaymentInstrument;\n\ninterface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport enum UntrustedShippingCardVerificationType {\n CVV = 'cvv',\n PAN = 'pan',\n}\n\nexport interface CardInstrument extends BaseInstrument {\n brand: string;\n expiryMonth: string;\n expiryYear: string;\n iin: string;\n last4: string;\n type: 'card';\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType;\n}\n\ninterface BaseAccountInstrument extends BaseInstrument {\n method: string;\n type: 'account' | 'bank';\n}\n\nexport interface PayPalInstrument extends BaseAccountInstrument {\n externalId: string;\n method: 'paypal';\n}\n\nexport interface AchInstrument extends BaseAccountInstrument {\n issuer: string;\n accountNumber: string;\n type: 'bank';\n method: 'ach' | 'ecp';\n}\n\nexport interface BankInstrument extends BaseAccountInstrument {\n accountNumber: string;\n issuer: string;\n iban: string;\n method: string;\n type: 'bank';\n}\n\nexport type AccountInstrument = PayPalInstrument | BankInstrument | AchInstrument;\n\nexport interface VaultAccessToken {\n vaultAccessToken: string;\n vaultAccessExpiry: number;\n}\n\nexport interface SessionContext {\n customerId: number;\n storeId: string;\n currencyCode?: string;\n}\n\nexport interface InstrumentRequestContext extends SessionContext {\n authToken: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { CustomerAddress } from '../../../customer';\nimport { Country } from '../../../geography';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { PaymentProviderCustomerActionCreator } from '../../../payment-provider-customer';\nimport { CardInstrument } from '../../../payment/instrument';\nimport { UntrustedShippingCardVerificationType } from '../../../payment/instrument/instrument';\nimport { BraintreeInitializationData } from '../../../payment/strategies/braintree';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class BraintreeFastlaneShippingStrategy implements ShippingStrategy {\n private _browserStorage: BrowserStorage;\n\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _braintreeIntegrationService: BraintreeIntegrationService,\n ) {\n this._browserStorage = new BrowserStorage('paypalFastlane');\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { methodId, braintreefastlane } = options || {};\n const { onPayPalFastlaneAddressChange } = braintreefastlane || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const customer = state.customer.getCustomerOrThrow();\n\n if (!customer.isGuest) {\n return Promise.resolve(this._store.getState());\n }\n\n try {\n if (this._shouldRunAuthenticationFlow()) {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const { clientToken, isFastlaneStylingEnabled } =\n paymentMethod?.initializationData || {};\n\n if (!clientToken) {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n }\n\n const paypalFastlaneStylesSettings = isFastlaneStylingEnabled\n ? paymentMethod?.initializationData?.fastlaneStyles\n : undefined;\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStylesSettings,\n braintreefastlane?.styles,\n );\n\n await this._runAuthenticationFlowOrThrow(methodId, fastlaneStyles);\n }\n\n if (\n typeof onPayPalFastlaneAddressChange === 'function' &&\n (await this._shouldUseBraintreeFastlaneShippingComponent(methodId))\n ) {\n onPayPalFastlaneAddressChange(() =>\n this._handleBraintreeFastlaneShippingAddressChange(),\n );\n }\n } catch (error) {\n // Info: we should not throw any error here to avoid\n // customer stuck on shipping step due to the payment provider\n // custom flow\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private _shouldRunAuthenticationFlow(): boolean {\n const state = this._store.getState();\n const cartId = state.cart.getCart()?.id;\n const paypalFastlaneSessionId = this._browserStorage.getItem('sessionId');\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n if (\n braintreePaymentProviderCustomer?.authenticationState ===\n BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return (\n !braintreePaymentProviderCustomer?.authenticationState &&\n paypalFastlaneSessionId === cartId\n );\n }\n\n private async _runAuthenticationFlowOrThrow(\n methodId: string,\n styles?: BraintreeFastlaneStylesOption,\n ): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const countries = state.countries.getCountries() || [];\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeIntegrationService.initialize(clientToken);\n\n const braintreeFastlane = await this._braintreeIntegrationService.getBraintreeFastlane(\n cart?.id,\n config?.testMode,\n styles,\n );\n\n const customerEmail =\n state.customer.getCustomer()?.email || state.billingAddress.getBillingAddress()?.email;\n\n if (!customerEmail) {\n return;\n }\n\n const { lookupCustomerByEmail, triggerAuthenticationFlow } = braintreeFastlane.identity;\n\n const { customerContextId } = await lookupCustomerByEmail(customerEmail);\n\n if (!customerContextId) {\n return;\n }\n\n const { authenticationState, profileData } = await triggerAuthenticationFlow(\n customerContextId,\n );\n\n if (authenticationState === BraintreeFastlaneAuthenticationState.CANCELED) {\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses: [],\n instruments: [],\n }),\n );\n\n this._browserStorage.removeItem('sessionId');\n\n return;\n }\n\n const paypalBillingAddress = this._getPayPalBillingAddress(profileData);\n const paypalShippingAddress = profileData.shippingAddress;\n const paypalPhoneNumber = profileData.shippingAddress.phoneNumber;\n\n const shippingAddress = this._mapPayPalToBcAddress(\n paypalShippingAddress,\n countries,\n paypalPhoneNumber,\n );\n const billingAddress = this._mapPayPalToBcAddress(\n paypalBillingAddress,\n countries,\n paypalPhoneNumber,\n );\n\n if (billingAddress && shippingAddress) {\n const addresses = this._mergeShippingAndBillingAddresses(\n shippingAddress,\n billingAddress,\n );\n const instrument = this._mapPayPalToBcInstrument(methodId, profileData.card);\n const instruments = instrument ? [instrument] : [];\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n }),\n );\n\n if (billingAddress) {\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress({\n ...billingAddress,\n id: String(billingAddress.id),\n }),\n );\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n }\n }\n }\n\n private _getPayPalBillingAddress(\n profileData: BraintreeFastlaneProfileData,\n ): BraintreeFastlaneAddress {\n const { name, card } = profileData;\n const paypalBillingAddress = card.paymentSource.card.billingAddress;\n\n return {\n ...paypalBillingAddress,\n firstName: paypalBillingAddress.firstName || name?.firstName,\n lastName: paypalBillingAddress.lastName || name?.lastName,\n };\n }\n\n private _getCountryNameByCountryCode(countryCode: string, countries: Country[]): string {\n const matchedCountry = countries.find((country) => country.code === countryCode);\n\n return matchedCountry?.name || '';\n }\n\n private _mapPayPalToBcAddress(\n address: BraintreeFastlaneAddress,\n countries: Country[],\n phoneNumber?: string,\n customFields?: CustomerAddress['customFields'],\n ): CustomerAddress {\n return {\n id: Number(Date.now()),\n type: 'paypal-address',\n firstName: address.firstName || '',\n lastName: address.lastName || '',\n company: address.company || '',\n address1: address.streetAddress,\n address2: address.extendedAddress || '',\n city: address.locality,\n stateOrProvince: address.region,\n stateOrProvinceCode: address.region,\n country: this._getCountryNameByCountryCode(address.countryCodeAlpha2, countries),\n countryCode: address.countryCodeAlpha2,\n postalCode: address.postalCode,\n phone: phoneNumber || '',\n customFields: customFields || [],\n };\n }\n\n private _normalizeAddress(address: CustomerAddress | BraintreeFastlaneAddress) {\n return omit(address, ['id']);\n }\n\n private _mergeShippingAndBillingAddresses(\n shippingAddress: CustomerAddress,\n billingAddress: CustomerAddress,\n ): CustomerAddress[] {\n const addressesAreTheSame = isEqual(\n this._normalizeAddress(shippingAddress),\n this._normalizeAddress(billingAddress),\n );\n\n return addressesAreTheSame ? [shippingAddress] : [shippingAddress, billingAddress];\n }\n\n private _mapPayPalToBcInstrument(\n methodId: string,\n instrument?: BraintreeFastlaneVaultedInstrument,\n ): CardInstrument | undefined {\n if (!instrument) {\n return;\n }\n\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.CVV,\n type: 'card',\n };\n }\n\n /**\n *\n * Braintree Fastlane shipping address change through Fastlane external popup\n *\n */\n private async _handleBraintreeFastlaneShippingAddressChange(): Promise<\n CustomerAddress | undefined\n > {\n const state = this._store.getState();\n const countries = state.countries.getCountries() || [];\n const braintreeFastlane = await this._braintreeIntegrationService.getBraintreeFastlane();\n\n const { selectionChanged, selectedAddress } =\n await braintreeFastlane.profile.showShippingAddressSelector();\n\n if (selectionChanged) {\n const state = this._store.getState();\n const shipping = state.shippingAddress.getShippingAddressesOrThrow();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreeFastlaneCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const shippingAddress = this._mapPayPalToBcAddress(\n selectedAddress,\n countries,\n selectedAddress.phoneNumber,\n shipping[0].customFields,\n );\n\n if (shippingAddress) {\n const paymentProviderCustomerAddresses = this._filterAddresses([\n shippingAddress,\n ...(braintreeFastlaneCustomer.addresses || []),\n ]);\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n ...braintreeFastlaneCustomer,\n addresses: paymentProviderCustomerAddresses,\n }),\n );\n\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n\n return shippingAddress;\n }\n }\n\n return undefined;\n }\n\n /**\n *\n * This method is responsible for filtering BT Fastlane addresses if they are the same\n * and returns an array of addresses to use them for shipping and/or billing address selections\n * so the customer will be able to use addresses from BT Fastlane in checkout flow\n *\n */\n private _filterAddresses(addresses: Array): CustomerAddress[] {\n return addresses.reduce(\n (customerAddresses: CustomerAddress[], currentAddress: CustomerAddress | undefined) => {\n if (!currentAddress) {\n return customerAddresses;\n }\n\n const sameAddressInTheArray = customerAddresses.some((customerAddress) =>\n this._isEqualAddresses(customerAddress, currentAddress),\n );\n\n return sameAddressInTheArray\n ? customerAddresses\n : [...customerAddresses, currentAddress];\n },\n [],\n );\n }\n\n private _isEqualAddresses(\n firstAddress: CustomerAddress,\n secondAddress: CustomerAddress,\n ): boolean {\n return isEqual(this._normalizeAddress(firstAddress), this._normalizeAddress(secondAddress));\n }\n\n private async _shouldUseBraintreeFastlaneShippingComponent(methodId: string): Promise {\n const state = this._store.getState();\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n // Info: to avoid loading payment method we should check for values\n // that does not require api calls first\n if (\n !!braintreePaymentProviderCustomer &&\n braintreePaymentProviderCustomer !== BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n const paymentMethod = await this._getBraintreePaymentMethodOrThrow(methodId);\n\n return !!paymentMethod?.initializationData?.isFastlaneEnabled;\n }\n\n return false;\n }\n\n private async _getBraintreePaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n const newState = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n return newState.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n return paymentMethod;\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class DefaultShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","import { CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalCommerceAcceleratedCheckoutCustomer,\n isPayPalFastlaneCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { PaymentProviderCustomerActionCreator } from '../../../payment-provider-customer';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class PayPalCommerceFastlaneShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _paypalCommerceSdk: PayPalCommerceSdk,\n private _paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { methodId, paypalcommercefastlane } = options || {};\n const { onPayPalFastlaneAddressChange, styles } = paypalcommercefastlane || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const customer = state.customer.getCustomerOrThrow();\n\n if (!customer?.isGuest) {\n return Promise.resolve(this._store.getState());\n }\n\n try {\n if (this._shouldAuthenticateUserWithFastlane()) {\n await this._initializePayPalSdk(methodId, styles);\n await this._authenticateUserWithFastlaneOtp(methodId);\n }\n\n if (\n typeof onPayPalFastlaneAddressChange === 'function' &&\n this._shouldUsePayPalFastlaneShippingComponent()\n ) {\n await this._initializePayPalSdk(methodId, styles);\n onPayPalFastlaneAddressChange(() => this._handlePayPalShippingAddressChange());\n }\n } catch (error) {\n // Info: we should not throw any error here to avoid customer stuck on\n // shipping step due to the payment provider custom flow\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private async _getPayPalPaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n const newState = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n return newState.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n return paymentMethod;\n }\n\n private _getPayPalCustomerAuthenticationState(): string | undefined {\n const state = this._store.getState();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomerOrThrow();\n const paypalCommercePaymentProviderCustomer = isPayPalCommerceAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return paypalCommercePaymentProviderCustomer.authenticationState;\n }\n\n private _shouldAuthenticateUserWithFastlane(): boolean {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const paypalConnectSessionId = this._paypalCommerceFastlaneUtils.getStorageSessionId();\n\n const customerAuthenticationState = this._getPayPalCustomerAuthenticationState();\n\n return !customerAuthenticationState && paypalConnectSessionId === cart.id;\n }\n\n private _shouldUsePayPalFastlaneShippingComponent(): boolean {\n const customerAuthenticationState = this._getPayPalCustomerAuthenticationState();\n\n return (\n !!customerAuthenticationState &&\n customerAuthenticationState !== PayPalFastlaneAuthenticationState.CANCELED\n );\n }\n\n private async _initializePayPalSdk(\n methodId: string,\n styles?: PayPalFastlaneStylesOption,\n ): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n\n const paymentMethod = await this._getPayPalPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod?.initializationData || {};\n const isTestModeEnabled = !!isDeveloperModeApplicable;\n\n const fastlaneStyles = getFastlaneStyles(\n isFastlaneStylingEnabled ? paymentMethod?.initializationData?.fastlaneStyles : {},\n styles,\n );\n\n const paypalFastlaneSdk = await this._paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this._paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n fastlaneStyles,\n );\n }\n\n private async _authenticateUserWithFastlaneOtp(methodId: string): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const customerEmail = state.customer.getCustomer()?.email;\n const billingAddressEmail = state.billingAddress.getBillingAddress()?.email;\n const email = customerEmail || billingAddressEmail || '';\n\n const { customerContextId } = await this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(\n email,\n );\n\n const authenticationResult =\n await this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, billingAddress, shippingAddress, instruments } =\n this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n }),\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cart.id,\n );\n\n if (billingAddress) {\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress({\n ...billingAddress,\n id: String(billingAddress.id),\n }),\n );\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n }\n }\n\n /**\n *\n * PayPal Fastlane shipping address change through Fastlane external popup\n *\n */\n private async _handlePayPalShippingAddressChange(): Promise {\n const paypalFastlaneSdk = this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const { selectionChanged, selectedAddress } =\n await paypalFastlaneSdk.profile.showShippingAddressSelector();\n\n if (selectionChanged) {\n const state = this._store.getState();\n const shipping = state.shippingAddress.getShippingAddressesOrThrow();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const shippingAddress = this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(\n selectedAddress.address,\n selectedAddress.name,\n selectedAddress.phoneNumber,\n shipping[0].customFields,\n );\n\n const paymentProviderCustomerAddresses =\n this._paypalCommerceFastlaneUtils.filterAddresses([\n shippingAddress,\n ...(paypalFastlaneCustomer.addresses || []),\n ]);\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n ...paypalFastlaneCustomer,\n addresses: paymentProviderCustomerAddresses,\n }),\n );\n\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n\n return shippingAddress;\n }\n\n return undefined;\n }\n}\n","import { CustomFont, PaymentIntent, StripeConfigurationOptions } from '../stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n };\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport interface AddressOptions {\n city?: string;\n country?: string;\n state?: string;\n postal_code?: string;\n line1?: string;\n line2?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postal_code: string;\n country: string;\n };\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): void;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n };\n rules?: {\n '.Input'?: {\n borderColor?: string;\n color?: string;\n boxShadow?: string;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\ninterface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n\nexport enum StripeUPEPaymentIntentStatus {\n REQUIRES_PAYMENT_METHOD = 'requires_payment_method',\n REQUIRES_CONFIRMATION = 'requires_confirmation',\n REQUIRES_ACTION = 'requires_action',\n PROCESSING = 'processing',\n SUCCEEDED = 'succeeded',\n CANCELED = 'canceled',\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n DisplayName,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class StripeUPEShippingStrategy implements ShippingStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const {\n container,\n gatewayId,\n methodId,\n onChangeShipping,\n getStyles,\n availableCountries,\n getStripeState,\n } = options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n if (\n !paymentMethod ||\n !paymentMethod.initializationData.stripePublishableKey ||\n !paymentMethod.clientToken\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions;\n const styles = getStyles && getStyles();\n\n const {\n form: { getShippingAddressFields },\n shippingAddress: { getShippingAddress },\n } = this._store.getState();\n\n const shippingFields = getShippingAddressFields([], '');\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {\n variables: {\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n };\n }\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n appearance,\n });\n\n const shipping = getShippingAddress();\n const shippingPhoneField = shippingFields.find((field) => field.name === 'phone');\n let option: StripeElementsCreateOptions = {\n mode: StripeFormMode.SHIPPING,\n allowedCountries: [availableCountries],\n fields: {\n phone: 'always',\n },\n validation: {\n phone: {\n required:\n shippingPhoneField && shippingPhoneField.required ? 'always' : 'never',\n },\n },\n display: {\n name: DisplayName.SPLIT,\n },\n };\n\n if (shipping) {\n const {\n stateOrProvinceCode,\n countryCode,\n lastName,\n firstName,\n phone,\n address1,\n address2,\n city,\n postalCode,\n } = shipping;\n const stripeState =\n stateOrProvinceCode && countryCode\n ? getStripeState(countryCode, stateOrProvinceCode)\n : stateOrProvinceCode;\n\n option = {\n ...option,\n defaultValues: {\n firstName,\n lastName,\n phone,\n address: {\n line1: address1,\n line2: address2,\n city,\n state: stripeState,\n postal_code: postalCode,\n country: countryCode,\n },\n },\n };\n }\n\n let shippingAddressElement = this._stripeElements.getElement(StripeElementType.SHIPPING);\n\n if (shippingAddressElement) {\n shippingAddressElement.destroy();\n }\n\n shippingAddressElement = this._stripeElements.create(StripeElementType.SHIPPING, option);\n\n shippingAddressElement.on('change', (event: StripeEventType) => {\n if (!('isNewAddress' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n if (event.complete || event.isNewAddress) {\n if (this.sendData) {\n clearTimeout(this.sendData);\n }\n\n this.sendData = setTimeout(() => {\n onChangeShipping({\n ...event,\n phoneFieldRequired: shippingPhoneField\n ? shippingPhoneField.required\n : false,\n });\n }, 1000);\n }\n });\n\n shippingAddressElement.mount(`#${container}`);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n /* The new shipping component by StripeLink has a small bug, when the component is unmounted,\n Stripe does not save the shipping, to solve this, we will leave it mounted,\n and once it is fixed will be unmounted again */\n\n // this._stripeElements?.getElement(StripeElementType.SHIPPING)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { SignInEmail } from './signin-email';\n\nexport enum SignInEmailActionType {\n SendSignInEmailRequested = 'SEND_SIGNIN_EMAIL_REQUESTED',\n SendSignInEmailSucceeded = 'SEND_SIGNIN_EMAIL_SUCCEEDED',\n SendSignInEmailFailed = 'SEND_SIGNIN_EMAIL_FAILED',\n}\nexport type SendSignInEmailAction =\n | SendSignInEmailRequestedAction\n | SendSignInEmailSucceededAction\n | SendSignInEmailFailedAction;\n\nexport interface SendSignInEmailRequestedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailRequested;\n}\n\nexport interface SendSignInEmailSucceededAction extends Action {\n type: SignInEmailActionType.SendSignInEmailSucceeded;\n}\n\nexport interface SendSignInEmailFailedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { SignInEmailRequestBody } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailRequestSender from './signin-email-request-sender';\n\nexport default class SignInEmailActionCreator {\n constructor(private _requestSender: SignInEmailRequestSender) {}\n\n sendSignInEmail(\n emailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SignInEmailActionType.SendSignInEmailRequested)),\n defer(async () => {\n const { body } = await this._requestSender.sendSignInEmail(emailRequest, options);\n\n return createAction(SignInEmailActionType.SendSignInEmailSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SignInEmailActionType.SendSignInEmailFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { SignInEmail, SignInEmailRequestBody } from './signin-email';\n\nexport default class SignInEmailRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n sendSignInEmail(\n { email, redirectUrl }: SignInEmailRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/login.php?action=passwordless_login';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: {\n email,\n redirect_url:\n redirectUrl || parseUrl(window.top ? window.top.location.href : '').pathname,\n },\n headers,\n timeout,\n });\n }\n}\n","import { toSingleLine } from '../utility';\n\nexport default class ErrorMessageTransformer {\n constructor(private _messageCustomizer: (type: TError) => string) {}\n\n transform(error: TError): TError {\n error.message = toSingleLine(this._messageCustomizer(error));\n\n return error;\n }\n}\n","export default function toSingleLine(input?: string) {\n if (!input) {\n return '';\n }\n\n return input\n .split(/(?:\\r\\n|\\n|\\r)/)\n .map((line) => line.replace(/^\\s+/gm, ''))\n .join(' ')\n .trim();\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable } from 'rxjs';\n\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { AddressRequestBody } from '../address';\nimport { BillingAddressActionCreator, BillingAddressRequestBody } from '../billing';\nimport { DataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorMessageTransformer } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator } from '../config';\nimport { CouponActionCreator, GiftCertificateActionCreator } from '../coupon';\nimport {\n CustomerAccountRequestBody,\n CustomerActionCreator,\n CustomerAddressRequestBody,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerRequestOptions,\n CustomerStrategyActionCreator,\n ExecutePaymentMethodCheckoutOptions,\n GuestCredentials,\n} from '../customer';\nimport {\n ExtensionActionCreator,\n ExtensionCommandMap,\n ExtensionEventBroadcaster,\n ExtensionMessenger,\n ExtensionRegion,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n PaymentInitializeOptions,\n PaymentMethodActionCreator,\n PaymentRequestOptions,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { InstrumentActionCreator } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentAssignmentRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n PickupOptionActionCreator,\n PickupOptionRequestBody,\n ShippingCountryActionCreator,\n ShippingInitializeOptions,\n ShippingRequestOptions,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestBody } from '../signin-email';\nimport { SpamProtectionActionCreator, SpamProtectionOptions } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\nimport { Subscriptions, SubscriptionsActionCreator } from '../subscription';\n\nimport { CheckoutRequestBody } from './checkout';\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutParams from './checkout-params';\nimport CheckoutSelectors from './checkout-selectors';\nimport CheckoutStore from './checkout-store';\nimport createCheckoutServiceErrorTransformer from './create-checkout-service-error-transformer';\n\n/**\n * Responsible for completing the checkout process for the current customer.\n *\n * This object can be used to collect all information that is required for\n * checkout, such as shipping and billing information. It can also be used to\n * retrieve the current checkout state and subscribe to its changes.\n */\n@bind\nexport default class CheckoutService {\n private _errorTransformer: ErrorMessageTransformer;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _storeProjection: DataStoreProjection,\n private _extensionMessenger: ExtensionMessenger,\n private _extensionEventBroadcaster: ExtensionEventBroadcaster,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _configActionCreator: ConfigActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _countryActionCreator: CountryActionCreator,\n private _couponActionCreator: CouponActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _errorActionCreator: ErrorActionCreator,\n private _giftCertificateActionCreator: GiftCertificateActionCreator,\n private _instrumentActionCreator: InstrumentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _pickupOptionActionCreator: PickupOptionActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n private _signInEmailActionCreator: SignInEmailActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _subscriptionsActionCreator: SubscriptionsActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n private _extensionActionCreator: ExtensionActionCreator,\n ) {\n this._errorTransformer = createCheckoutServiceErrorTransformer();\n }\n\n /**\n * Returns a snapshot of the current checkout state.\n *\n * The method returns a new instance every time there is a change in the\n * checkout state. You can query the state by calling any of its getter\n * methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.data.getOrder());\n * console.log(state.errors.getSubmitOrderError());\n * console.log(state.statuses.isSubmittingOrder());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutSelectors {\n return this._storeProjection.getState();\n }\n\n /**\n * Notifies all subscribers with the current state.\n *\n * When this method gets called, the subscribers get called regardless if\n * they have any filters applied.\n */\n notifyState(): void {\n this._storeProjection.notifyState();\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the checkout state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.data.getCart());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.data.getCart();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.data.getCart())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutSelectors) => void,\n ...filters: Array<(state: CheckoutSelectors) => any>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n /**\n * Loads the current checkout.\n *\n * This method can only be called if there is an active checkout. Also, it\n * can only retrieve data that belongs to the current customer. When it is\n * successfully executed, you can retrieve the data by calling\n * `CheckoutStoreSelector#getCheckout`.\n *\n * ```js\n * const state = await service.loadCheckout('0cfd6c06-57c3-4e29-8d7a-de55cc8a9052');\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param id - The identifier of the checkout to load, or the default checkout if not provided.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n loadCheckout(\n id?: string,\n options?: RequestOptions,\n ): Promise {\n return this._dispatch(\n id\n ? this._checkoutActionCreator.loadCheckout(id, options)\n : this._checkoutActionCreator.loadDefaultCheckout(options),\n );\n }\n\n /**\n * Updates specific properties of the current checkout.\n *\n * ```js\n * const state = await service.updateCheckout(checkout);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param payload - The checkout properties to be updated.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n updateCheckout(\n payload: CheckoutRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._checkoutActionCreator.updateCheckout(payload, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads an order by an id.\n *\n * The method can only retrieve an order if the order belongs to the current\n * customer. If it is successfully executed, the data can be retrieved by\n * calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.loadOrder(123);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param orderId - The identifier of the order to load.\n * @param options - Options for loading the order.\n * @returns A promise that resolves to the current state.\n */\n loadOrder(orderId: number, options?: RequestOptions): Promise {\n const loadCheckoutAction = this._orderActionCreator.loadOrder(orderId, options);\n const formFieldsAction = this._formFieldsActionCreator.loadFormFields(options);\n const loadConfigAction = this._configActionCreator.loadConfig(options);\n\n return Promise.all([\n this._dispatch(loadCheckoutAction),\n this._dispatch(loadConfigAction, { queueId: 'config' }),\n this._dispatch(formFieldsAction, { queueId: 'formFields' }),\n ]).then(() => this.getState());\n }\n\n /**\n * Submits an order, thereby completing a checkout process.\n *\n * Before you can submit an order, you must initialize the payment method\n * chosen by the customer by calling `CheckoutService#initializePayment`.\n *\n * ```js\n * await service.initializePayment({ methodId: 'braintree' });\n * await service.submitOrder({\n * payment: {\n * methodId: 'braintree',\n * paymentData: {\n * ccExpiry: { month: 10, year: 20 },\n * ccName: 'BigCommerce',\n * ccNumber: '4111111111111111',\n * ccCvv: 123,\n * },\n * },\n * });\n * ```\n *\n * You are not required to include `paymentData` if the order does not\n * require additional payment details. For example, the customer has already\n * entered their payment details on the cart page using one of the hosted\n * payment methods, such as PayPal. Or the customer has applied a gift\n * certificate that exceeds the grand total amount.\n *\n * If the order is submitted successfully, you can retrieve the newly\n * created order by calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.submitOrder(payload);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param payload - The request payload to submit for the current order.\n * @param options - Options for submitting the current order.\n * @returns A promise that resolves to the current state.\n */\n submitOrder(payload: OrderRequestBody, options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.execute(payload, options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Finalizes the submission process for an order.\n *\n * This method is only required for certain hosted payment methods that\n * require a customer to enter their credit card details on their website.\n * You need to call this method once the customer has redirected back to\n * checkout in order to complete the checkout process.\n *\n * If the method is called before order finalization is required or for a\n * payment method that does not require order finalization, an error will be\n * thrown. Conversely, if the method is called successfully, you should\n * immediately redirect the customer to the order confirmation page.\n *\n * ```js\n * try {\n * await service.finalizeOrderIfNeeded();\n *\n * window.location.assign('/order-confirmation');\n * } catch (error) {\n * if (error.type !== 'order_finalization_not_required') {\n * throw error;\n * }\n * }\n * ```\n *\n * @param options - Options for finalizing the current order.\n * @returns A promise that resolves to the current state.\n * @throws `OrderFinalizationNotRequiredError` error if order finalization\n * is not required for the current order at the time of execution.\n */\n finalizeOrderIfNeeded(options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.finalize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of payment methods available for checkout.\n *\n * If a customer enters their payment details before navigating to the\n * checkout page (i.e.: using PayPal checkout button on the cart page), only\n * one payment method will be available for the customer - the selected\n * payment method. Otherwise, by default, all payment methods configured by\n * the merchant will be available for the customer.\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethods();\n *\n * console.log(state.data.getPaymentMethods());\n * ```\n *\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethods(options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethods(options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a list of payment methods for given ids.\n *\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethodsById(['applepay']);\n *\n * console.log(state.data.getPaymentMethodOrThrow('applepay'));\n * ```\n *\n * @param methodIds - The identifier for the payment methods to load.\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethodByIds(\n methodIds: string[],\n options?: RequestOptions,\n ): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethodsById(methodIds, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a payment method by an id.\n *\n * This method does not work with multi-option payment providers. Due to its\n * limitation, it is deprecated and will be removed in the future.\n *\n * @deprecated\n * @internal\n * @param methodId - The identifier for the payment method to load.\n * @param options - Options for loading the payment method.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethod(methodId: string, options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethod(methodId, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Initializes the payment step of a checkout process.\n *\n * Before a payment method can accept payment details, it must first be\n * initialized. Some payment methods require you to provide additional\n * initialization options. For example, you can provide an element ID for\n * Amazon Pay if you want users to be able to select a different payment\n * method by clicking on the element.\n *\n * ```js\n * await service.initializePayment({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editButtonId: 'edit-button',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializePayment(options: PaymentInitializeOptions): Promise {\n const action = this._paymentStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * De-initializes the payment step of a checkout process.\n *\n * The method should be called once you no longer require a payment method\n * to be initialized. It can perform any necessary clean-up behind the\n * scene, i.e.: remove DOM nodes or event handlers that are attached as a\n * result of payment initialization.\n *\n * ```js\n * await service.deinitializePayment({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializePayment(options: PaymentRequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of countries available for billing.\n *\n * Once you make a successful request, you will be able to retrieve the list\n * of countries by calling `CheckoutStoreSelector#getBillingCountries`.\n *\n * ```js\n * const state = await service.loadBillingCountries();\n *\n * console.log(state.data.getBillingCountries());\n * ```\n *\n * @param options - Options for loading the available billing countries.\n * @returns A promise that resolves to the current state.\n */\n loadBillingCountries(options?: RequestOptions): Promise {\n const action = this._countryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'billingCountries' });\n }\n\n /**\n * Loads a list of countries available for shipping.\n *\n * The list is determined based on the shipping zones configured by a\n * merchant. Once you make a successful call, you will be able to retrieve\n * the list of available shipping countries by calling\n * `CheckoutStoreSelector#getShippingCountries`.\n *\n * ```js\n * const state = await service.loadShippingCountries();\n *\n * console.log(state.data.getShippingCountries());\n * ```\n *\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadShippingCountries(options?: RequestOptions): Promise {\n const action = this._shippingCountryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'shippingCountries' });\n }\n\n /**\n * Loads a list of pickup options for a given criteria.\n *\n * ```js\n * const consignmentId = '1';\n * const searchArea = {\n * radius: {\n * value: 1.4,\n * unit: 'KM'\n * },\n * coordinates: {\n * latitude: 1.4,\n * longitude: 0\n * },\n * };\n * const state = await service.loadPickupOptions({ consignmentId, searchArea });\n *\n * console.log(state.data.getPickupOptions(consignmentId, searchArea));\n * ```\n *\n * @alpha\n * @param query - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadPickupOptions(query: PickupOptionRequestBody): Promise {\n const action = this._pickupOptionActionCreator.loadPickupOptions(query);\n\n return this._dispatch(action, { queueId: 'pickupOptions' });\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their billing address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getBillingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadBillingAddressFields();\n *\n * console.log(state.data.getBillingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the billing address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadBillingAddressFields(options?: RequestOptions): Promise {\n return this.loadBillingCountries(options);\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their shipping address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getShippingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadShippingAddressFields();\n *\n * console.log(state.data.getShippingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the shipping address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadShippingAddressFields(options?: RequestOptions): Promise {\n return this.loadShippingCountries(options);\n }\n\n /**\n * Initializes the sign-in step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, have their own sign-in flow. In\n * order to support them, this method must be called.\n *\n * ```js\n * await service.initializeCustomer({\n * methodId: 'amazonpay',\n * amazonpay: {\n * container: 'signInButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeCustomer(options?: CustomerInitializeOptions): Promise {\n const action = this._customerStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * De-initializes the sign-in step of a checkout process.\n *\n * It should be called once you no longer want to prompt customers to sign\n * in. It can perform any necessary clean-up behind the scene, i.e.: remove\n * DOM nodes or event handlers that are attached as a result of customer\n * initialization.\n *\n * ```js\n * await service.deinitializeCustomer({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Sends a email that contains a single-use sign-in link. When a valid links is clicked,\n * signs in the customer without requiring any password, redirecting them to the account page if no redirectUrl is provided.\n *\n *\n * ```js\n * checkoutService.sendSignInEmail({ email: 'foo@bar.com', redirectUrl: 'checkout' });\n * ```\n *\n * @param signInEmailRequest - The sign-in email request values.\n * @param options - Options for the send email request.\n * @returns A promise that resolves to the current state.\n */\n sendSignInEmail(\n signInEmailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._signInEmailActionCreator.sendSignInEmail(signInEmailRequest, options);\n\n return this._dispatch(action, { queueId: 'signInEmail' });\n }\n\n /**\n * Creates a customer account.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAccount({\n * email: 'foo@bar.com',\n * firstName: 'Foo',\n * lastName: 'Bar',\n * password: 'password',\n * acceptsMarketingEmails: true,\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccount` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAccount - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAccount(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createCustomer(customerAccount, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Creates a customer account address.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAddress({\n * firstName: 'Foo',\n * lastName: 'Bar',\n * address1: '55 Market St',\n * stateOrProvinceCode: 'CA',\n * countryCode: 'US',\n * postalCode: '90110',\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccountAddress` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAddress - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createAddress(customerAddress, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Updates the subscriptions associated to an email.\n *\n * @param subscriptions - The email and associated subscriptions to update.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Promise {\n const action = this._subscriptionsActionCreator.updateSubscriptions(subscriptions, options);\n\n return this._dispatch(action, { queueId: 'subscriptions' });\n }\n\n /**\n * Continues to check out as a guest.\n *\n * If your Checkout Settings allow it, your customers could continue the checkout as guests (without signing in).\n * If you have enabled the checkout setting \"Prompt existing accounts to sign in\", this information is\n * exposed as part of the [Customer](../interfaces/customer.md) object.\n *\n * Once they provide their email address, it will be stored as\n * part of their [billing address](../interfaces/billingaddress.md).\n *\n * @param credentials - The guest credentials to use, with optional subscriptions.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): Promise {\n const action = this._billingAddressActionCreator.continueAsGuest(credentials, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Signs into a customer's registered account.\n *\n * Once the customer is signed in successfully, the checkout state will be\n * populated with information associated with the customer, such as their\n * saved addresses. You can call `CheckoutStoreSelector#getCustomer` to\n * retrieve the data.\n *\n * ```js\n * const state = await service.signInCustomer({\n * email: 'foo@bar.com',\n * password: 'password123',\n * });\n *\n * console.log(state.data.getCustomer());\n * ```\n *\n * @param credentials - The credentials to be used for signing in the customer.\n * @param options - Options for signing in the customer.\n * @returns A promise that resolves to the current state.\n */\n signInCustomer(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.signIn(credentials, options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Signs out the current customer if they are previously signed in.\n *\n * Once the customer is successfully signed out, the checkout state will be\n * reset automatically.\n *\n * ```js\n * const state = await service.signOutCustomer();\n *\n * // The returned object should not contain information about the previously signed-in customer.\n * console.log(state.data.getCustomer());\n * ```\n *\n * When a store has \"Allow customers to access their cart across multiple devices\" enabled, signing out\n * will remove the cart/checkout data from the current session. An error with type=\"checkout_not_available\" will be thrown.\n *\n * ```js\n * try {\n * await service.signOutCustomer();\n * } catch (error) {\n * if (error.type === 'checkout_not_available') {\n * window.top.location.assign('/');\n * }\n * }\n * ```\n *\n * @param options - Options for signing out the customer.\n * @returns A promise that resolves to the current state.\n */\n signOutCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.signOut(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Executes custom checkout of the priority payment method.\n *\n * Some payment methods, such as Bolt, can use their own checkout\n * with autofilled customers data, to make checkout passing process\n * easier and faster for customers with Bolt account.\n *\n * ```js\n * await service.executePaymentMethodCheckout({\n * methodId: 'bolt',\n * fallback: () => {},\n * });\n * ```\n *\n * @param options - Options for executing payment method checkout.\n * @returns A promise that resolves to the current state.\n */\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.executePaymentMethodCheckout(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Loads a list of shipping options available for checkout.\n *\n * Available shipping options can only be determined once a customer\n * provides their shipping address. If the method is executed successfully,\n * `CheckoutStoreSelector#getShippingOptions` can be called to retrieve the\n * list of shipping options.\n *\n * ```js\n * const state = await service.loadShippingOptions();\n *\n * console.log(state.data.getShippingOptions());\n * ```\n *\n * @param options - Options for loading the available shipping options.\n * @returns A promise that resolves to the current state.\n */\n loadShippingOptions(options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.loadShippingOptions(options);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the shipping step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, can provide shipping\n * information to be used for checkout. In order to support them, this\n * method must be called.\n *\n * ```js\n * await service.initializeShipping({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editAddressButtonId: 'changeAddressButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeShipping(options?: ShippingInitializeOptions): Promise {\n const action = this._shippingStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * De-initializes the shipping step of a checkout process.\n *\n * It should be called once you no longer need to collect shipping details.\n * It can perform any necessary clean-up behind the scene, i.e.: remove DOM\n * nodes or event handlers that are attached as a result of shipping\n * initialization.\n *\n * ```js\n * await service.deinitializeShipping({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeShipping(options?: ShippingRequestOptions): Promise {\n const action = this._shippingStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for the current address.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectShippingOption('address-id', 'shipping-option-id');\n *\n * console.log(state.data.getSelectedShippingOption());\n * ```\n *\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectShippingOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.selectOption(shippingOptionId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the shipping address for the current checkout.\n *\n * When a customer updates their shipping address for an order, they will\n * see an updated list of shipping options and the cost for each option,\n * unless no options are available. If the update is successful, you can\n * call `CheckoutStoreSelector#getShippingAddress` to retrieve the address.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateShippingAddress(address);\n *\n * console.log(state.data.getShippingAddress());\n * ```\n *\n * @param address - The address to be used for shipping.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateShippingAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.updateAddress(address, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Creates consignments given a list.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * When consignments are created, an updated list of shipping options will\n * become available for each consignment, unless no options are available.\n * If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve the updated list of\n * consignments.'\n *\n * Beware that if a consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.createConsignments(consignments);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignments - The list of consignments to be created.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.createConsignments(consignments, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Deletes a consignment\n *\n * ```js\n * const state = await service.deleteConsignment('55c96cda6f04c');\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The ID of the consignment to be deleted\n * @param options - Options for the consignment delete request\n * @returns A promise that resolves to the current state.\n */\n deleteConsignment(consignmentId: string, options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.deleteConsignment(consignmentId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates a specific consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#selectShippingOption`.\n *\n * When a shipping address for a consignment is updated, an updated list of\n * shipping options will become available for the consignment, unless no\n * options are available. If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve updated list of\n * consignments.\n *\n * Beware that if the updated consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateConsignment(consignment);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateConsignment(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that assigns items to be shipped to a specific address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and assigns the provided items. If no consignment matches the address, a new one\n * will be created.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n assignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.assignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that unassigns items from a specific shipping address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and unassigns the specified items. If the consignment ends up with no line items\n * after the unassignment, it will be deleted.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n unassignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.unassignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for a given consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectConsignmentShippingOption(consignmentId, optionId);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The identified of the consignment to be updated.\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectConsignmentShippingOption(\n consignmentId: string,\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateShippingOption(\n {\n id: consignmentId,\n shippingOptionId,\n },\n options,\n );\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the billing address for the current checkout.\n *\n * A customer must provide their billing address before they can proceed to\n * pay for their order.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateBillingAddress(address);\n *\n * console.log(state.data.getBillingAddress());\n * ```\n *\n * @param address - The address to be used for billing.\n * @param options - Options for updating the billing address.\n * @returns A promise that resolves to the current state.\n */\n updateBillingAddress(\n address: Partial,\n options: RequestOptions = {},\n ): Promise {\n const action = this._billingAddressActionCreator.updateAddress(address, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies or removes customer's store credit code to the current checkout.\n *\n * Once the store credit gets applied, the outstanding balance will be adjusted accordingly.\n *\n * ```js\n * const state = await service.applyStoreCredit(true);\n *\n * console.log(state.data.getCheckout().outstandingBalance);\n * ```\n *\n * @param options - Options for applying store credit.\n * @returns A promise that resolves to the current state.\n */\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n const action = this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a coupon code to the current checkout.\n *\n * Once the coupon code gets applied, the quote for the current checkout will\n * be adjusted accordingly. The same coupon code cannot be applied more than\n * once.\n *\n * ```js\n * await service.applyCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to apply to the current checkout.\n * @param options - Options for applying the coupon code.\n * @returns A promise that resolves to the current state.\n */\n applyCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.applyCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a coupon code from the current checkout.\n *\n * Once the coupon code gets removed, the quote for the current checkout will\n * be adjusted accordingly.\n *\n * ```js\n * await service.removeCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to remove from the current checkout.\n * @param options - Options for removing the coupon code.\n * @returns A promise that resolves to the current state.\n */\n removeCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.removeCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a gift certificate to the current checkout.\n *\n * Once the gift certificate gets applied, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.applyGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to apply to the current checkout.\n * @param options - Options for applying the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n applyGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.applyGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a gift certificate from an order.\n *\n * Once the gift certificate gets removed, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.removeGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to remove from the current checkout.\n * @param options - Options for removing the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n removeGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.removeGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads a list of payment instruments associated with a customer.\n *\n * Once the method has been called successfully, you can retrieve the list\n * of payment instruments by calling `CheckoutStoreSelector#getInstruments`.\n * If the customer does not have any payment instruments on record, i.e.:\n * credit card, you will get an empty list instead.\n *\n * ```js\n * const state = service.loadInstruments();\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n loadInstruments(): Promise {\n const action = this._instrumentActionCreator.loadInstruments();\n\n return this._dispatch(action);\n }\n\n /**\n * Deletes a payment instrument by an id.\n *\n * Once an instrument gets removed, it can no longer be retrieved using\n * `CheckoutStoreSelector#getInstruments`.\n *\n * ```js\n * const state = service.deleteInstrument('123');\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns A promise that resolves to the current state.\n */\n deleteInstrument(instrumentId: string): Promise {\n const action = this._instrumentActionCreator.deleteInstrument(instrumentId);\n\n return this._dispatch(action).then(() => this.loadInstruments());\n }\n\n /**\n * Clear errors that have been collected from previous calls.\n *\n * ```js\n * const state = await service.clearError(error);\n *\n * console.log(state.errors.getError());\n * ```\n *\n * @param error - Specific error object to clear\n * @returns A promise that resolves to the current state.\n */\n clearError(error: Error): Promise {\n const action = this._errorActionCreator.clearError(error);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the spam protection for order creation.\n *\n * Note: Use `CheckoutService#executeSpamCheck` instead.\n * You do not need to call this method before calling\n * `CheckoutService#executeSpamCheck`.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails.\n *\n * ```js\n * await service.initializeSpamProtection();\n * ```\n *\n * @param options - Options for initializing spam protection.\n * @returns A promise that resolves to the current state.\n * @deprecated - Use CheckoutService#executeSpamCheck instead.\n */\n initializeSpamProtection(options: SpamProtectionOptions): Promise {\n const action = this._spamProtectionActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Verifies whether the current checkout is created by a human.\n *\n * Note: this method will do the initialization, therefore you do not\n * need to call `CheckoutService#initializeSpamProtection`\n * before calling this method.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails. You should call this method before\n * `submitOrder` method is called (i.e.: when the shopper\n * first gets to the payment step).\n *\n * **Note**: You need to enable Google ReCAPTCHA bot protection in your Checkout Settings.\n *\n * ```js\n * await service.executeSpamCheck();\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n executeSpamCheck(): Promise {\n const action = this._spamProtectionActionCreator.verifyCheckoutSpamProtection();\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Loads a list of extensions available for checkout.\n *\n * ```js\n * const state = await service.loadExtensions();\n *\n * console.log(state.data.getExtensions());\n * ```\n *\n * @alpha\n * @param options - Options for loading the extensions that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadExtensions(options?: RequestOptions): Promise {\n const action = this._extensionActionCreator.loadExtensions(options);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Renders an extension for a checkout extension region.\n * Currently, only one extension is allowed per region.\n *\n * @alpha\n * @param container - The ID of a container which the extension should be inserted.\n * @param region - The name of an area where the extension should be presented.\n * @returns A promise that resolves to the current state.\n */\n async renderExtension(container: string, region: ExtensionRegion): Promise {\n const action = this._extensionActionCreator.renderExtension(container, region);\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Manages the command handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the command.\n * @param command - The command to be handled.\n * @param handler - The handler function for the extension command.\n * @returns A function that, when called, will deregister the command handler.\n */\n handleExtensionCommand(\n extensionId: string,\n command: T,\n handler: (command: ExtensionCommandMap[T]) => void,\n ): () => void {\n return this._extensionMessenger.listen(extensionId, command, handler);\n }\n\n /**\n * Dispatches an action through the data store and returns the current state\n * once the action is dispatched.\n *\n * @param action - The action to dispatch.\n * @returns A promise that resolves to the current state.\n */\n private _dispatch(\n action: Action | Observable | ThunkAction,\n options?: { queueId?: string },\n ): Promise {\n return this._store\n .dispatch(action, options)\n .then(() => this.getState())\n .catch((error) => {\n throw this._errorTransformer.transform(error);\n });\n }\n}\n","import { ErrorMessageTransformer } from '../common/error';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../common/error/errors';\nimport { getEnvironment } from '../common/utility';\n\nexport type CheckoutServiceErrorType = MissingDataError | NotInitializedError;\nexport type CheckoutServiceErrorTransformer = ErrorMessageTransformer<\n CheckoutServiceErrorType | Error\n>;\n\nexport default function createCheckoutServiceErrorTransformer(\n isDevelopment: boolean = getEnvironment() === 'development',\n): CheckoutServiceErrorTransformer {\n return new ErrorMessageTransformer((error) => {\n if (!isDevelopment || !isCheckoutServiceError(error)) {\n return error.message;\n }\n\n switch (error.subtype || error.type) {\n case MissingDataErrorType.MissingConsignments:\n return `\n ${error.message}\n The data could be unavailable because no shipping address has been provided.\n To fix this, create a consignment or update the shipping address before performing\n the same action again.\n `;\n\n case MissingDataErrorType.MissingCart:\n case MissingDataErrorType.MissingCheckout:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \\`CheckoutService#loadCheckout\\`\n before performing the same action again.\n `;\n\n case MissingDataErrorType.MissingCheckoutConfig:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you need to make sure \\`CheckoutService\\` is initialized\n properly by calling \\`CheckoutService#loadCheckout\\` before performing any\n other actions.\n `;\n\n case MissingDataErrorType.MissingOrder:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \\`CheckoutService#loadOrder\\`\n before performing the same action again.\n `;\n\n case MissingDataErrorType.MissingOrderId:\n return `\n ${error.message}\n The data could be unavailable because no order has been created yet. You have\n to first create the order before you can perform the action.\n `;\n\n case MissingDataErrorType.MissingPaymentMethod:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server, or\n configured by the merchant yet. To fix the former issue, you can try calling\n \\`CheckoutService#loadPaymentMethods\\` before performing the same action again.\n `;\n\n case NotInitializedErrorType.CustomerNotInitialized:\n return `\n In order to initialize the customer step of checkout, you need to call\n \\`CheckoutService#initializeCustomer\\`. Afterwards, you should be able to\n submit customer details.\n `;\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return `\n ${error.message}\n In order to initialize the payment step of checkout, you need to call\n \\`CheckoutService#initializePayment\\`. Afterwards, you should be able to\n submit payment details.\n `;\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return `\n ${error.message}\n In order to initialize the shipping step of checkout, you need to call\n \\`CheckoutService#initializeShipping\\`. Afterwards, you should be able to\n submit shipping details.\n `;\n\n default:\n return error.message;\n }\n });\n}\n\nfunction isCheckoutServiceError(error: any): error is CheckoutServiceErrorType {\n return !!(error.subtype || error.type);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"reselect\");","import { memoize } from '@bigcommerce/memoize';\nimport { createSelector as defaultSelectorCreator } from 'reselect';\n\n/**\n * Decorate selector creators with the ability to memoize the return value of\n * their combiner if it is a function (which effectively works as a partially\n * applied combiner).\n */\nexport default function withMemoizedCombiner(\n creator: T,\n): T {\n return ((...args: any[]) => {\n const combiner = args.pop();\n\n // Reselect's default `createSelector` has many overloads. To avoid having\n // to redefine all of them, we're using `any` to bypass the typechecker.\n return (creator as any)(...args, (...combinerArgs: any[]) => {\n // Although there are many overloads, all of them have the last argument\n // as the combiner.\n const result = combiner(...combinerArgs);\n\n if (typeof result === 'function') {\n return memoize(result);\n }\n\n return result;\n });\n }) as T;\n}\n","import { createSelector as defaultSelectorCreator } from 'reselect';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\n/**\n * This is a decorated version of Reselect's default `createSelector` function.\n * If the return value of the combiner function is a function, it will create a\n * memorized version of that function and return it instead.\n */\nexport default withMemoizedCombiner(defaultSelectorCreator);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"shallowequal\");","import { createSelectorCreator, defaultMemoize } from 'reselect';\nimport shallowEqual from 'shallowequal';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\nconst createShallowEqualSelector = createSelectorCreator(defaultMemoize, (a: any, b: any) =>\n shallowEqual(a, b),\n);\n\nexport default withMemoizedCombiner(createShallowEqualSelector);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if there is an unexpected error and it is not possible to\n * recover from unless the shopper creates a new checkout session.\n */\nexport default class UnrecoverableError extends RequestError {\n constructor(response: Response, message?: string) {\n super(response, {\n message:\n message ||\n 'An unexpected error has occurred. The checkout process cannot continue as a result.',\n });\n\n this.name = 'UnrecoverableError';\n this.type = 'unrecoverable';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromInternalErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || body.detail || body.title || message,\n errors: errors.length\n ? errors.map((message) => ({ code: body.type, message }))\n : [{ code: body.type, message: body.detail || body.title }],\n });\n}\n\nfunction joinErrors(errors: string[]): string | undefined {\n return errors\n .reduce((result: string[], error) => {\n if (error) {\n return [...result, error];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\nimport { last } from 'lodash';\n\nimport {\n ErrorResponseBody,\n InternalErrorResponseBody,\n StorefrontErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n mapFromInternalErrorResponse,\n mapFromPaymentErrorResponse,\n mapFromStorefrontErrorResponse,\n RequestError,\n TimeoutError,\n} from './errors';\n\nexport default class RequestErrorFactory {\n private _factoryMethods: { [key: string]: ErrorFactoryMethod } = {};\n\n constructor() {\n this.register('default', (response, message) => new RequestError(response, { message }));\n this.register('internal', (response, message) =>\n mapFromInternalErrorResponse(response, message),\n );\n this.register('storefront', (response, message) =>\n mapFromStorefrontErrorResponse(response, message),\n );\n this.register('payment', (response, message) =>\n mapFromPaymentErrorResponse(response, message),\n );\n this.register('timeout', (response) => new TimeoutError(response));\n }\n\n register(type: string, factoryMethod: ErrorFactoryMethod): void {\n this._factoryMethods[type] = factoryMethod;\n }\n\n createError(response: Response, message?: string): RequestError {\n const factoryMethod =\n this._factoryMethods[this._getType(response)] || this._factoryMethods.default;\n\n return factoryMethod(response, message);\n }\n\n private _getType(response: Response): string {\n if (response.status === 0) {\n return 'timeout';\n }\n\n if (this._isStorefrontErrorResponseBody(response.body)) {\n return 'storefront';\n }\n\n if (this._isInternalErrorResponseBody(response.body)) {\n const internalType = last(response.body.type.split('/'));\n\n return internalType && this._factoryMethods[internalType] ? internalType : 'internal';\n }\n\n const error = last(response.body && response.body.errors);\n\n if (error && error.code && this._factoryMethods[error.code]) {\n return error.code;\n }\n\n return 'payment';\n }\n\n private _isStorefrontErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is StorefrontErrorResponseBody {\n const storefrontErrorResponse = errorResponse as StorefrontErrorResponseBody;\n\n return (\n !this._isInternalErrorResponseBody(errorResponse) &&\n typeof storefrontErrorResponse.title === 'string' &&\n typeof storefrontErrorResponse.type === 'string' &&\n typeof storefrontErrorResponse.status === 'number' &&\n typeof storefrontErrorResponse.detail === 'string'\n );\n }\n\n private _isInternalErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is InternalErrorResponseBody {\n const internalErrorResponse = errorResponse as InternalErrorResponseBody;\n\n return (\n typeof internalErrorResponse.errors === 'object' &&\n typeof internalErrorResponse.title === 'string' &&\n typeof internalErrorResponse.type === 'string' &&\n typeof internalErrorResponse.status === 'number'\n );\n }\n}\n\nexport type ErrorFactoryMethod = (response: Response, message?: string) => RequestError;\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromStorefrontErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n\n return new RequestError(response, {\n message: message || body.detail || body.title,\n errors: [\n {\n code: body.code || body.type,\n message: body.detail || body.title,\n },\n ],\n });\n}\n","import { isPlainObject, omitBy, transform } from 'lodash';\n\nexport default function omitDeep(\n object: any,\n predicate: (value: any, key: string) => boolean,\n): any {\n if (Array.isArray(object)) {\n return object.map((value) => omitDeep(value, predicate));\n }\n\n if (isPlainObject(object)) {\n return transform(\n omitBy(object, predicate),\n (result, value, key) => {\n result[key] = omitDeep(value, predicate);\n },\n {} as { [key: string]: any },\n );\n }\n\n return object;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { omitDeep } from '../utility';\n\nimport { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default function clearErrorReducer<\n TState extends { [key: string]: any },\n TAction extends Action,\n>(state: TState, action: TAction): TState | undefined {\n if (isClearErrorAction(action)) {\n return omitDeep(state, (value) => value === action.payload);\n }\n\n return state;\n}\n\nfunction isClearErrorAction(action: Action): action is ClearErrorAction {\n return action.type === ErrorActionType.ClearError;\n}\n","export interface CompareOptions {\n keyFilter?(key: string): boolean;\n}\n\nexport default function isEqual(objectA: any, objectB: any, options?: CompareOptions): boolean {\n if (objectA === objectB) {\n return true;\n }\n\n if (objectA && objectB && typeof objectA === 'object' && typeof objectB === 'object') {\n if (Array.isArray(objectA) && Array.isArray(objectB)) {\n return isArrayEqual(objectA, objectB, options);\n }\n\n if (Array.isArray(objectA) || Array.isArray(objectB)) {\n return false;\n }\n\n if (objectA instanceof Date && objectB instanceof Date) {\n return isDateEqual(objectA, objectB);\n }\n\n if (objectA instanceof Date || objectB instanceof Date) {\n return false;\n }\n\n if (objectA instanceof RegExp && objectB instanceof RegExp) {\n return isRegExpEqual(objectA, objectB);\n }\n\n if (objectA instanceof RegExp || objectB instanceof RegExp) {\n return false;\n }\n\n return isObjectEqual(objectA, objectB, options);\n }\n\n return objectA === objectB;\n}\n\nfunction isRegExpEqual(objectA: RegExp, objectB: RegExp): boolean {\n return objectA.toString() === objectB.toString();\n}\n\nfunction isDateEqual(objectA: Date, objectB: Date): boolean {\n return objectA.getTime() === objectB.getTime();\n}\n\nfunction isArrayEqual(objectA: any[], objectB: any[], options?: CompareOptions): boolean {\n if (objectA.length !== objectB.length) {\n return false;\n }\n\n for (let index = 0, length = objectA.length; index < length; index++) {\n if (!isEqual(objectA[index], objectB[index], options)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isObjectEqual(\n objectA: { [key: string]: any },\n objectB: { [key: string]: any },\n options?: CompareOptions,\n): boolean {\n const filter = options && options.keyFilter;\n const keysA = filter ? Object.keys(objectA).filter(filter) : Object.keys(objectA);\n const keysB = filter ? Object.keys(objectB).filter(filter) : Object.keys(objectB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let index = 0, length = keysA.length; index < length; index++) {\n const key = keysA[index];\n\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) {\n return false;\n }\n\n if (!isEqual(objectA[key], objectB[key], options)) {\n return false;\n }\n }\n\n return true;\n}\n","import isEqual from './is-equal';\n\n/**\n * Replace the current value with a new value if the former is different to the\n * latter.\n */\nexport default function replace(currentValue: T, newValue?: T): T {\n if (newValue === undefined || isEqual(currentValue, newValue)) {\n return currentValue;\n }\n\n return newValue;\n}\n","import isEqual from './is-equal';\n\n/**\n * Set a new value to an object under a key if the new value is different to the\n * current value of the key.\n */\nexport default function objectSet(\n object: T | undefined,\n key: K,\n value: T[K],\n): T {\n if (\n object &&\n Object.prototype.hasOwnProperty.call(object, key) &&\n isEqual(object[key], value)\n ) {\n return object;\n }\n\n return {\n ...(object as any),\n [key]: value,\n };\n}\n","import BillingAddress from './billing-address';\n\nexport default interface BillingAddressState {\n data?: BillingAddress;\n errors: BillingAddressErrorsState;\n statuses: BillingAddressStatusesState;\n}\n\nexport interface BillingAddressErrorsState {\n loadError?: Error;\n updateError?: Error;\n continueAsGuestError?: Error;\n}\n\nexport interface BillingAddressStatusesState {\n isLoading?: boolean;\n isUpdating?: boolean;\n isContinuingAsGuest?: boolean;\n}\n\nexport const DEFAULT_STATE: BillingAddressState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet, replace } from '../common/utility';\nimport { OrderAction } from '../order';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport BillingAddress from './billing-address';\nimport { BillingAddressAction, BillingAddressActionType } from './billing-address-actions';\nimport BillingAddressState, {\n BillingAddressErrorsState,\n BillingAddressStatusesState,\n DEFAULT_STATE,\n} from './billing-address-state';\n\nexport default function billingAddressReducer(\n state: BillingAddressState = DEFAULT_STATE,\n action: Action,\n): BillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: BillingAddress | undefined,\n action: CheckoutAction | BillingAddressAction | OrderAction,\n): BillingAddress | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: BillingAddressErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case BillingAddressActionType.ContinueAsGuestRequested:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(errors, 'continueAsGuestError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n return objectSet(errors, 'continueAsGuestError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: BillingAddressStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case BillingAddressActionType.ContinueAsGuestRequested:\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isContinuingAsGuest', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(statuses, 'isContinuingAsGuest', false);\n\n default:\n return statuses;\n }\n}\n","import { isArray } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\nimport replace from './replace';\n\nexport interface ArrayReplaceOptions {\n matchObject(objectA: any, objectB: any): boolean;\n}\n\nfunction arrayReplace(\n currentArray: T[] | undefined,\n newArray: T[],\n options?: ArrayReplaceOptions,\n): T[];\nfunction arrayReplace(\n currentArray: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): undefined;\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined;\n\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined {\n const { matchObject = (a: any, b: any) => a.id !== undefined && a.id === b.id } = options || {};\n\n // Return the new array if the current array does not exist\n if (!currentArray) {\n return newArray;\n }\n\n // If the new array does not exist, or the current array is strictly equal\n // to the new array, exit early and return the current array so that the\n // object reference doesn't change\n if (!newArray || currentArray === newArray) {\n return currentArray;\n }\n\n // Otherwise, try to replace the items of the current array with the new\n // array. If the item from the two arrays are the same, keep the current\n // one. Do it recursively until all arrays are replaced.\n let sameAsCurrentCount = 0;\n let sameAsNewCount = 0;\n\n const countSameAsReplaced = (replacedValue: T, currentValue: T, newValue: T): T => {\n sameAsCurrentCount += replacedValue === currentValue ? 1 : 0;\n sameAsNewCount += replacedValue === newValue ? 1 : 0;\n\n return replacedValue;\n };\n\n const result = newArray.map((newItem, index) => {\n const currentItem = currentArray && currentArray[index];\n\n if (isPlainObject(currentItem) && isPlainObject(newItem)) {\n if (matchObject(currentItem, newItem)) {\n return countSameAsReplaced(objectMerge(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }\n\n if (isArray(currentItem) && isArray(newItem)) {\n return countSameAsReplaced(arrayReplace(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }) as T[];\n\n // If all items in the result are identical to the current array, and the\n // current array and the new array have the same size, simply return the\n // current array instead of the result.\n if (\n sameAsCurrentCount === newArray.length &&\n currentArray &&\n currentArray.length === newArray.length\n ) {\n return currentArray;\n }\n\n // If all items in the result are identical to the new array, simply return\n // the new array.\n if (sameAsNewCount === newArray.length) {\n return newArray;\n }\n\n return result;\n}\n\nexport default arrayReplace;\n","import { isArray } from 'lodash';\n\nimport arrayReplace from './array-replace';\nimport isPlainObject from './is-plain-object';\nimport objectSet from './object-set';\n\nfunction objectMerge(currentObject: T, newObject?: Partial): T;\nfunction objectMerge(\n currentObject: T | undefined,\n newObject: Partial,\n): Partial;\nfunction objectMerge(currentObject?: T, newObject?: Partial): T | undefined;\n\nfunction objectMerge(\n currentObject?: T,\n newObject?: Partial,\n): T | Partial | undefined {\n if (!currentObject) {\n return newObject;\n }\n\n // If the new object does not exist but the current object does, or the new\n // object is strictly equal to the current object, return the current object\n if (!newObject || currentObject === newObject) {\n return currentObject;\n }\n\n // If both objects exist, but some values might be different, perform a merge.\n // Retain values that are equal and only replace them with the new values if\n // they are different.\n return (Object.keys(newObject) as Array).reduce((result, key) => {\n const currentValue = result[key];\n const newValue = newObject[key];\n\n if (isPlainObject(currentValue) && isPlainObject(newValue)) {\n return objectSet(result, key, objectMerge(currentValue, newValue));\n }\n\n if (isArray(currentValue) && isArray(newValue)) {\n return objectSet(result, key, arrayReplace(currentValue, newValue) as any);\n }\n\n return objectSet(result, key, newValue as any);\n }, currentObject);\n}\n\nexport default objectMerge;\n","import Cart from './cart';\n\nexport default interface CartState {\n data?: Cart;\n errors: CartErrorsState;\n statuses: CartStatusesState;\n}\n\nexport interface CartErrorsState {\n loadError?: Error;\n}\n\nexport interface CartStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CartState = {\n errors: {},\n statuses: {},\n};\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadPaymentMethodAction } from '../payment';\n\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport enum CheckoutButtonActionType {\n InitializeButtonFailed = 'INITIALIZE_BUTTON_FAILED',\n InitializeButtonRequested = 'INITIALIZE_BUTTON_REQUESTED',\n InitializeButtonSucceeded = 'INITIALIZE_BUTTON_SUCCEEDED',\n\n DeinitializeButtonFailed = 'DEINITIALIZE_BUTTON_FAILED',\n DeinitializeButtonRequested = 'DEINITIALIZE_BUTTON_REQUESTED',\n DeinitializeButtonSucceeded = 'DEINITIALIZE_BUTTON_SUCCEEDED',\n}\n\nexport type CheckoutButtonAction = InitializeButtonAction | DeinitializeButtonAction;\n\nexport type InitializeButtonAction =\n | InitializeButtonRequestedAction\n | InitializeButtonSucceededAction\n | InitializeButtonFailedAction\n | LoadPaymentMethodAction;\n\nexport type DeinitializeButtonAction =\n | DeinitializeButtonRequestedAction\n | DeinitializeButtonSucceededAction\n | DeinitializeButtonFailedAction;\n\nexport interface CheckoutButtonActionMeta {\n methodId: CheckoutButtonMethodType;\n}\n\nexport interface InitializeButtonActionMeta extends CheckoutButtonActionMeta {\n containerId: string;\n}\n\nexport interface InitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonRequested;\n}\n\nexport interface InitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonSucceeded;\n}\n\nexport interface InitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.InitializeButtonFailed;\n}\n\nexport interface DeinitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonRequested;\n}\n\nexport interface DeinitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonSucceeded;\n}\n\nexport interface DeinitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonFailed;\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Cart from './cart';\nimport CartState, { CartErrorsState, CartStatusesState, DEFAULT_STATE } from './cart-state';\n\nexport default function cartReducer(state: CartState = DEFAULT_STATE, action: Action): CartState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Cart | undefined,\n action:\n | BillingAddressAction\n | CheckoutAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction,\n): Cart | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectMerge(data, action.payload && action.payload.cart);\n\n default:\n return data;\n }\n}\n\nfunction statusesReducer(\n statuses: CartStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction,\n): CartStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n\nfunction errorsReducer(\n errors: CartErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction,\n): CartErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n","import { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonState {\n data: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonDataState | undefined;\n };\n errors: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonErrorsState | undefined;\n };\n statuses: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonStatusesState | undefined;\n };\n}\n\nexport interface CheckoutButtonDataState {\n initializedContainers: {\n [key: string]: boolean;\n };\n}\n\nexport interface CheckoutButtonErrorsState {\n initializeError?: Error;\n deinitializeError?: Error;\n}\n\nexport interface CheckoutButtonStatusesState {\n isInitializing?: boolean;\n isDeinitializing?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutButtonState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { CheckoutButtonAction, CheckoutButtonActionType } from './checkout-button-actions';\nimport CheckoutButtonState, {\n CheckoutButtonDataState,\n CheckoutButtonErrorsState,\n CheckoutButtonStatusesState,\n DEFAULT_STATE,\n} from './checkout-button-state';\n\nconst DEFAULT_DATA_STATE: CheckoutButtonDataState = { initializedContainers: {} };\nconst DEFAULT_ERROR_STATE: CheckoutButtonErrorsState = {};\nconst DEFAULT_STATUS_STATE: CheckoutButtonStatusesState = {};\n\nexport default function checkoutButtonReducer(\n state: CheckoutButtonState = DEFAULT_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n errors: combineReducers({\n [action.meta.methodId]: errorsReducer,\n }),\n statuses: combineReducers({\n [action.meta.methodId]: statusesReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutButtonDataState = DEFAULT_DATA_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonDataState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n if (!action.meta || !action.meta.containerId) {\n return data;\n }\n\n return objectMerge(data, {\n initializedContainers: {\n [action.meta.containerId]: true,\n },\n });\n\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(data, 'initializedContainers', {});\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CheckoutButtonErrorsState = DEFAULT_ERROR_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonErrorsState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(errors, 'initializeError', undefined);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n return objectSet(errors, 'initializeError', action.payload);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(errors, 'deinitializeError', undefined);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n return objectSet(errors, 'deinitializeError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutButtonStatusesState = DEFAULT_STATUS_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonStatusesState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n return objectSet(statuses, 'isInitializing', true);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(statuses, 'isInitializing', false);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n return objectSet(statuses, 'isDeinitializing', true);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(statuses, 'isDeinitializing', false);\n\n default:\n return statuses;\n }\n}\n","import Config from './config';\n\nexport default interface ConfigState {\n data?: Config;\n meta?: ConfigMetaState;\n errors: ConfigErrorsState;\n statuses: ConfigStatusesState;\n}\n\nexport interface ConfigMetaState {\n externalSource?: string;\n variantIdentificationToken?: string;\n host?: string;\n locale?: string;\n}\n\nexport interface ConfigErrorsState {\n loadError?: Error;\n}\n\nexport interface ConfigStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ConfigState = {\n meta: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Config from './config';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\nimport ConfigState, { ConfigErrorsState, ConfigStatusesState, DEFAULT_STATE } from './config-state';\n\nexport default function configReducer(\n state: ConfigState = DEFAULT_STATE,\n action: Action,\n): ConfigState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Config | undefined, action: LoadConfigAction): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConfigErrorsState = DEFAULT_STATE.errors,\n action: LoadConfigAction,\n): ConfigErrorsState {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ConfigActionType.LoadConfigFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConfigStatusesState = DEFAULT_STATE.statuses,\n action: LoadConfigAction,\n): ConfigStatusesState {\n switch (action.type) {\n case ConfigActionType.LoadConfigRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConfigActionType.LoadConfigSucceeded:\n case ConfigActionType.LoadConfigFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport Coupon from './coupon';\n\nexport default interface CouponState {\n data?: Coupon[];\n errors: CouponErrorsState;\n statuses: CouponStatusesState;\n}\n\nexport interface CouponErrorsState {\n applyCouponError?: RequestError;\n removeCouponError?: RequestError;\n}\n\nexport interface CouponStatusesState {\n isApplyingCoupon?: boolean;\n isRemovingCoupon?: boolean;\n}\n\nexport const DEFAULT_STATE: CouponState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Coupon from './coupon';\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport CouponState, { CouponErrorsState, CouponStatusesState, DEFAULT_STATE } from './coupon-state';\n\nexport default function couponReducer(\n state: CouponState = DEFAULT_STATE,\n action: Action,\n): CouponState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Coupon[] | undefined,\n action: CouponAction | CheckoutAction | OrderAction | ConsignmentAction,\n): Coupon[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return arrayReplace(data, action.payload && action.payload.coupons);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: CouponErrorsState = {}, action: CouponAction): CouponErrorsState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n case CouponActionType.ApplyCouponSucceeded:\n return objectSet(errors, 'applyCouponError', undefined);\n\n case CouponActionType.ApplyCouponFailed:\n return objectSet(errors, 'applyCouponError', action.payload);\n\n case CouponActionType.RemoveCouponRequested:\n case CouponActionType.RemoveCouponSucceeded:\n return objectSet(errors, 'removeCouponError', undefined);\n\n case CouponActionType.RemoveCouponFailed:\n return objectSet(errors, 'removeCouponError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CouponStatusesState = {},\n action: CouponAction,\n): CouponStatusesState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n return objectSet(statuses, 'isApplyingCoupon', true);\n\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.ApplyCouponFailed:\n return objectSet(statuses, 'isApplyingCoupon', false);\n\n case CouponActionType.RemoveCouponRequested:\n return objectSet(statuses, 'isRemovingCoupon', true);\n\n case CouponActionType.RemoveCouponSucceeded:\n case CouponActionType.RemoveCouponFailed:\n return objectSet(statuses, 'isRemovingCoupon', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport GiftCertificate from './gift-certificate';\n\nexport default interface GiftCertificateState {\n data?: GiftCertificate[];\n errors: GiftCertificateErrorsState;\n statuses: GiftCertificateStatusesState;\n}\n\nexport interface GiftCertificateErrorsState {\n applyGiftCertificateError?: RequestError;\n removeGiftCertificateError?: RequestError;\n}\n\nexport interface GiftCertificateStatusesState {\n isApplyingGiftCertificate?: boolean;\n isRemovingGiftCertificate?: boolean;\n}\n\nexport const DEFAULT_STATE: GiftCertificateState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport GiftCertificate from './gift-certificate';\nimport { GiftCertificateAction, GiftCertificateActionType } from './gift-certificate-actions';\nimport GiftCertificateState, {\n DEFAULT_STATE,\n GiftCertificateErrorsState,\n GiftCertificateStatusesState,\n} from './gift-certificate-state';\n\nexport default function giftCertificateReducer(\n state: GiftCertificateState = DEFAULT_STATE,\n action: Action,\n): GiftCertificateState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: GiftCertificate[] | undefined,\n action: CheckoutAction | GiftCertificateAction | ConsignmentAction | CouponAction,\n): GiftCertificate[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return arrayReplace(data, action.payload && action.payload.giftCertificates);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: GiftCertificateErrorsState = DEFAULT_STATE.errors,\n action: GiftCertificateAction,\n): GiftCertificateErrorsState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n return objectSet(errors, 'applyGiftCertificateError', undefined);\n\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(errors, 'applyGiftCertificateError', action.payload);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectSet(errors, 'removeGiftCertificateError', undefined);\n\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(errors, 'removeGiftCertificateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: GiftCertificateStatusesState = DEFAULT_STATE.statuses,\n action: GiftCertificateAction,\n): GiftCertificateStatusesState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n return objectSet(statuses, 'isApplyingGiftCertificate', true);\n\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(statuses, 'isApplyingGiftCertificate', false);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n return objectSet(statuses, 'isRemovingGiftCertificate', true);\n\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(statuses, 'isRemovingGiftCertificate', false);\n\n default:\n return statuses;\n }\n}\n","import Customer from './customer';\n\nexport default interface CustomerState {\n data?: Customer;\n statuses: CustomerStatusesState;\n errors: CustomerErrorsState;\n}\n\nexport interface CustomerErrorsState {\n createError?: Error;\n createAddressError?: Error;\n}\n\nexport interface CustomerStatusesState {\n isCreating?: boolean;\n isCreatingAddress?: boolean;\n}\n\nexport const DEFAULT_STATE: CustomerState = {\n errors: {},\n statuses: {},\n};\n","import { combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressActionType, ContinueAsGuestAction } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Customer from './customer';\nimport {\n CustomerAction,\n CustomerActionType,\n StripeLinkAuthenticatedAction,\n} from './customer-actions';\nimport CustomerState, {\n CustomerErrorsState,\n CustomerStatusesState,\n DEFAULT_STATE,\n} from './customer-state';\n\ntype ReducerActionType =\n | CheckoutAction\n | ContinueAsGuestAction\n | CustomerAction\n | StripeLinkAuthenticatedAction;\n\nexport default function customerReducer(\n state: CustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): CustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Customer | undefined, action: ReducerActionType): Customer | undefined {\n switch (action.type) {\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectMerge(data, action.payload && action.payload.customer);\n\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CustomerErrorsState = DEFAULT_STATE.errors,\n action: ReducerActionType,\n): CustomerErrorsState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case CustomerActionType.CreateCustomerFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(errors, 'createAddressError', undefined);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n return objectSet(errors, 'createAddressError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStatusesState = DEFAULT_STATE.statuses,\n action: ReducerActionType,\n): CustomerStatusesState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case CustomerActionType.CreateCustomerFailed:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(statuses, 'isCreating', false);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n return objectSet(statuses, 'isCreatingAddress', true);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(statuses, 'isCreatingAddress', false);\n\n default:\n return statuses;\n }\n}\n","export default interface CustomerStrategyState {\n data: CustomerStrategyDataState;\n errors: CustomerStrategyErrorsState;\n statuses: CustomerStrategyStatusesState;\n}\n\nexport interface CustomerStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface CustomerStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeErrors?: { [key: string]: Error };\n initializeMethodId?: string;\n signInError?: Error;\n signInMethodId?: string;\n signOutError?: Error;\n signOutMethodId?: string;\n executePaymentMethodCheckoutError?: Error;\n executePaymentMethodCheckoutMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface CustomerStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isSigningIn?: boolean;\n isSigningOut?: boolean;\n signInMethodId?: string;\n signOutMethodId?: string;\n isExecutingPaymentMethodCheckout?: boolean;\n executePaymentMethodCheckoutMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: CustomerStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { CustomerStrategyAction, CustomerStrategyActionType } from './customer-strategy-actions';\nimport CustomerStrategyState, {\n CustomerStrategyDataState,\n CustomerStrategyErrorsState,\n CustomerStrategyStatusesState,\n DEFAULT_STATE,\n} from './customer-strategy-state';\n\nexport default function customerStrategyReducer(\n state: CustomerStrategyState = DEFAULT_STATE,\n action: Action,\n): CustomerStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CustomerStrategyDataState = DEFAULT_STATE.data,\n action: CustomerStrategyAction,\n): CustomerStrategyDataState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CustomerStrategyErrorsState = DEFAULT_STATE.errors,\n action: CustomerStrategyAction,\n): CustomerStrategyErrorsState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeErrors: { ...errors.initializeErrors },\n initializeMethodId: errors.initializeMethodId\n ? errors.initializeMethodId\n : undefined,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeErrors: {\n ...errors.initializeErrors,\n [action.meta && action.meta.methodId]: action.payload,\n },\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(errors, {\n signInError: undefined,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n return objectMerge(errors, {\n signInError: action.payload,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(errors, {\n signOutError: undefined,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n return objectMerge(errors, {\n signOutError: action.payload,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: undefined,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: action.payload,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n case CustomerStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStrategyStatusesState = DEFAULT_STATE.statuses,\n action: CustomerStrategyAction,\n): CustomerStrategyStatusesState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n return objectMerge(statuses, {\n isSigningIn: true,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(statuses, {\n isSigningIn: false,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n return objectMerge(statuses, {\n isSigningOut: true,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(statuses, {\n isSigningOut: false,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: true,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: false,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFinished:\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { Extension } from './extension';\n\nexport interface ExtensionState {\n data?: Extension[];\n errors: ExtensionErrorsState;\n statuses: ExtensionStatusesState;\n}\n\nexport interface ExtensionErrorsState {\n loadError?: Error;\n renderError?: Error;\n}\n\nexport interface ExtensionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ExtensionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport { Extension } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport {\n DEFAULT_STATE,\n ExtensionErrorsState,\n ExtensionState,\n ExtensionStatusesState,\n} from './extension-state';\n\nexport function extensionReducer(\n state: ExtensionState = DEFAULT_STATE,\n action: Action,\n): ExtensionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Extension[] | undefined,\n action: ExtensionAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ExtensionErrorsState = DEFAULT_STATE.errors,\n action: ExtensionAction,\n): ExtensionErrorsState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n case ExtensionActionType.LoadExtensionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ExtensionActionType.RenderExtensionRequested:\n case ExtensionActionType.RenderExtensionSucceeded:\n return objectSet(errors, 'renderError', undefined);\n\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ExtensionActionType.RenderExtensionFailed:\n return objectSet(errors, 'renderError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ExtensionStatusesState = DEFAULT_STATE.statuses,\n action: ExtensionAction,\n): ExtensionStatusesState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ExtensionActionType.LoadExtensionsSucceeded:\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n errors: FormFieldsErrorState;\n statuses: FormFieldsStatusesState;\n}\n\nexport interface FormFieldsErrorState {\n loadError?: Error;\n}\n\nexport interface FormFieldsStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: FormFieldsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { FormFields } from './form-field';\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsState, {\n DEFAULT_STATE,\n FormFieldsErrorState,\n FormFieldsStatusesState,\n} from './form-fields-state';\n\nexport default function formFieldsReducer(\n state: FormFieldsState = DEFAULT_STATE,\n action: Action,\n): FormFieldsState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: FormFields | undefined,\n action: LoadFormFieldsAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: FormFieldsErrorState = DEFAULT_STATE.errors,\n action: LoadFormFieldsAction,\n): FormFieldsErrorState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: FormFieldsStatusesState = DEFAULT_STATE.statuses,\n action: LoadFormFieldsAction,\n): FormFieldsStatusesState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import Country from './country';\n\nexport default interface CountryState {\n data?: Country[];\n errors: CountryErrorsState;\n statuses: CountryStatusesState;\n}\n\nexport interface CountryErrorsState {\n loadError?: Error;\n}\n\nexport interface CountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport Country from './country';\nimport { CountryActionType, LoadCountriesAction } from './country-actions';\nimport CountryState, {\n CountryErrorsState,\n CountryStatusesState,\n DEFAULT_STATE,\n} from './country-state';\n\nexport default function countryReducer(\n state: CountryState = DEFAULT_STATE,\n action: Action,\n): CountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case CountryActionType.LoadCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CountryErrorsState = DEFAULT_STATE.errors,\n action: LoadCountriesAction,\n): CountryErrorsState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n case CountryActionType.LoadCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CountryActionType.LoadCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadCountriesAction,\n): CountryStatusesState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CountryActionType.LoadCountriesSucceeded:\n case CountryActionType.LoadCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport { InternalOrderMeta, InternalOrderPayment } from './internal-order';\nimport Order from './order';\n\nexport default interface OrderState {\n data?: OrderDataState;\n meta?: OrderMetaState;\n errors: OrderErrorsState;\n statuses: OrderStatusesState;\n}\n\nexport type OrderDataState = Omit;\n\nexport interface OrderMetaState extends InternalOrderMeta {\n token?: string;\n orderToken?: string;\n callbackUrl?: string;\n payment?: InternalOrderPayment;\n}\n\nexport interface OrderErrorsState {\n loadError?: Error;\n submitError?: Error;\n finalizeError?: Error;\n}\n\nexport interface OrderStatusesState {\n isLoading?: boolean;\n isSubmitting?: boolean;\n isFinalizing?: boolean;\n}\n\nexport const DEFAULT_STATE: OrderState = {\n errors: {},\n meta: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { OrderAction, OrderActionType } from './order-actions';\nimport OrderState, {\n DEFAULT_STATE,\n OrderDataState,\n OrderErrorsState,\n OrderMetaState,\n OrderStatusesState,\n} from './order-state';\n\nexport default function orderReducer(\n state: OrderState = DEFAULT_STATE,\n action: Action,\n): OrderState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderDataState | undefined,\n action: OrderAction,\n): OrderDataState | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n return objectMerge(\n data,\n omit(action.payload, ['billingAddress', 'coupons']),\n ) as OrderDataState;\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: OrderMetaState | undefined,\n action: OrderAction,\n): OrderMetaState | undefined {\n switch (action.type) {\n case OrderActionType.FinalizeOrderSucceeded:\n case OrderActionType.SubmitOrderSucceeded:\n return objectMerge(meta, {\n ...action.meta,\n callbackUrl: action.payload && action.payload.order.callbackUrl,\n orderToken: action.payload && action.payload.order.token,\n payment: action.payload && action.payload.order && action.payload.order.payment,\n });\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: OrderErrorsState = DEFAULT_STATE.errors,\n action: OrderAction,\n): OrderErrorsState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: OrderStatusesState = DEFAULT_STATE.statuses,\n action: OrderAction,\n): OrderStatusesState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Address } from '../address';\n\nexport interface OrderBillingAddress extends Address {\n email?: string;\n}\n\nexport default interface OrderBillingAddressState {\n data?: OrderBillingAddress;\n}\n\nexport const DEFAULT_STATE: OrderBillingAddressState = {};\n","import { Action, combineReducers } from '@bigcommerce/data-store';\n\nimport { replace } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default function orderBillingAddressReducer(\n state: OrderBillingAddressState = DEFAULT_STATE,\n action: Action,\n): OrderBillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderBillingAddress | undefined,\n action: OrderAction,\n): OrderBillingAddress | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { PaymentAction, PaymentActionType } from './payment-actions';\nimport PaymentResponseBody from './payment-response-body';\nimport PaymentState from './payment-state';\n\nexport default function paymentReducer(\n state: PaymentState = {},\n action: PaymentAction,\n): PaymentState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentResponseBody | undefined,\n action: PaymentAction,\n): PaymentResponseBody | undefined {\n switch (action.type) {\n case PaymentActionType.SubmitPaymentSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n","import PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport default interface PaymentMethodState {\n data?: PaymentMethod[];\n meta?: PaymentMethodMeta;\n errors: PaymentMethodErrorsState;\n statuses: PaymentMethodStatusesState;\n}\n\nexport interface PaymentMethodErrorsState {\n loadMethodId?: string;\n loadError?: Error;\n loadMethodError?: Error;\n}\n\nexport interface PaymentMethodStatusesState {\n loadMethodId?: string;\n isLoading?: boolean;\n isLoadingMethod?: boolean;\n}\n\nexport const DEFAULT_STATE: PaymentMethodState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, mergeOrPush, objectMerge, objectSet } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, {\n DEFAULT_STATE,\n PaymentMethodErrorsState,\n PaymentMethodStatusesState,\n} from './payment-method-state';\n\nexport default function paymentMethodReducer(\n state: PaymentMethodState = DEFAULT_STATE,\n action: Action,\n): PaymentMethodState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentMethod[] | undefined,\n action: PaymentMethodAction,\n): PaymentMethod[] | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return mergeOrPush(\n data || [],\n action.payload,\n action.payload && {\n id: action.payload.id,\n gateway: action.payload.gateway,\n },\n );\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return arrayReplace(data, action.payload, {\n matchObject: (methodA, methodB) =>\n methodA.id === methodB.id && methodA.gateway === methodB.gateway,\n });\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: PaymentMethodMeta | undefined,\n action: PaymentMethodAction,\n): PaymentMethodMeta | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: PaymentMethodErrorsState = DEFAULT_STATE.errors,\n action: PaymentMethodAction,\n): PaymentMethodErrorsState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return objectMerge(errors, {\n loadMethodId: undefined,\n loadMethodError: undefined,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(errors, {\n loadMethodId: action.meta.methodId,\n loadMethodError: action.payload,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentMethodStatusesState = DEFAULT_STATE.statuses,\n action: PaymentMethodAction,\n): PaymentMethodStatusesState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n return objectMerge(statuses, {\n isLoadingMethod: true,\n loadMethodId: action.meta.methodId,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(statuses, {\n isLoadingMethod: false,\n loadMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { findIndex, pick, pickBy, ValueKeyIteratee } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\n\n/**\n * Push an item to an array if it doesn't exist in the array. Otherwise, merge\n * with the existing item in the array. This function always returns a new array.\n */\nexport default function mergeOrPush(array: T[], item?: T, predicate?: ValueKeyIteratee): T[] {\n if (!item) {\n return array;\n }\n\n const defaultPredicate = pick(item, 'id');\n const derivedPredicate: any =\n typeof predicate === 'object' ? pickBy(predicate) : predicate || defaultPredicate;\n const index = findIndex(array, derivedPredicate);\n const newArray = [...array];\n\n if (index === -1) {\n newArray.push(item);\n } else {\n const existingItem = array[index];\n\n newArray[index] =\n isPlainObject(existingItem) && isPlainObject(item)\n ? objectMerge(existingItem, item)\n : item;\n }\n\n return newArray;\n}\n","export default interface PaymentStrategyState {\n data: PaymentStrategyDataState;\n errors: PaymentStrategyErrorsState;\n statuses: PaymentStrategyStatusesState;\n}\n\nexport interface PaymentStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface PaymentStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n executeError?: Error;\n executeMethodId?: string;\n finalizeError?: Error;\n finalizeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface PaymentStrategyStatusesState {\n deinitializeMethodId?: string;\n executeMethodId?: string;\n finalizeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isExecuting?: boolean;\n isFinalizing?: boolean;\n isInitializing?: boolean;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: PaymentStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentStrategyAction, PaymentStrategyActionType } from './payment-strategy-actions';\nimport PaymentStrategyState, {\n DEFAULT_STATE,\n PaymentStrategyDataState,\n PaymentStrategyErrorsState,\n PaymentStrategyStatusesState,\n} from './payment-strategy-state';\n\nexport default function paymentStrategyReducer(\n state: PaymentStrategyState = DEFAULT_STATE,\n action: Action,\n): PaymentStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentStrategyDataState = DEFAULT_STATE.data,\n action: PaymentStrategyAction,\n): PaymentStrategyDataState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: true,\n },\n });\n }\n\n break;\n }\n\n case PaymentStrategyActionType.DeinitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: false,\n },\n });\n }\n }\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: PaymentStrategyErrorsState = DEFAULT_STATE.errors,\n action: PaymentStrategyAction,\n): PaymentStrategyErrorsState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.InitializeFailed: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeRequested:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeFailed: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.ExecuteRequested:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(errors, {\n executeError: undefined,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n return objectMerge(errors, {\n executeError: action.payload,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(errors, {\n finalizeError: undefined,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n return objectMerge(errors, {\n finalizeError: action.payload,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n case PaymentStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentStrategyStatusesState = DEFAULT_STATE.statuses,\n action: PaymentStrategyAction,\n): PaymentStrategyStatusesState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.InitializeFailed:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeRequested: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeFailed:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteRequested:\n return objectMerge(statuses, {\n isExecuting: true,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(statuses, {\n isExecuting: false,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n return objectMerge(statuses, {\n isFinalizing: true,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(statuses, {\n isFinalizing: false,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFinished:\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { PaymentProviderCustomer } from './payment-provider-customer';\n\nexport default interface PaymentProviderCustomerState {\n data: PaymentProviderCustomer;\n}\n\nexport const DEFAULT_STATE = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport {\n PaymentProviderCustomerType,\n UpdatePaymentProviderCustomerAction,\n} from './payment-provider-customer-actions';\nimport PaymentProviderCustomerState, { DEFAULT_STATE } from './payment-provider-customer-state';\n\ntype ReducerActionType = UpdatePaymentProviderCustomerAction;\n\nexport default function paymentProviderCustomerReducer(\n state: PaymentProviderCustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): PaymentProviderCustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentProviderCustomer = DEFAULT_STATE.data,\n action: ReducerActionType,\n): PaymentProviderCustomer {\n switch (action.type) {\n case PaymentProviderCustomerType.UpdatePaymentProviderCustomer:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import PaymentInstrument, { VaultAccessToken } from './instrument';\n\nexport default interface InstrumentState {\n data?: PaymentInstrument[];\n meta?: InstrumentMeta;\n errors: InstrumentErrorState;\n statuses: InstrumentStatusState;\n}\n\nexport interface InstrumentErrorState {\n deleteError?: Error;\n failedInstrument?: string;\n loadError?: Error;\n vaultError?: Error;\n}\n\nexport interface InstrumentStatusState {\n isDeleting?: boolean;\n isLoading?: boolean;\n isVaulting?: boolean;\n deletingInstrument?: string;\n}\n\nexport type InstrumentMeta = VaultAccessToken;\n\nexport const DEFAULT_STATE = {\n data: [],\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../../common/utility';\n\nimport PaymentInstrument from './instrument';\nimport { InstrumentAction, InstrumentActionType } from './instrument-actions';\nimport InstrumentState, {\n DEFAULT_STATE,\n InstrumentErrorState,\n InstrumentMeta,\n InstrumentStatusState,\n} from './instrument-state';\n\nexport default function instrumentReducer(\n state: InstrumentState = DEFAULT_STATE,\n action: Action,\n): InstrumentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentInstrument[] = DEFAULT_STATE.data,\n action: InstrumentAction,\n): PaymentInstrument[] {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return arrayReplace(data, (action.payload && action.payload.vaultedInstruments) || []);\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: InstrumentMeta | undefined,\n action: InstrumentAction,\n): InstrumentMeta | undefined {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: InstrumentErrorState = DEFAULT_STATE.errors,\n action: InstrumentAction,\n): InstrumentErrorState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(errors, {\n deleteError: undefined,\n failedInstrument: undefined,\n });\n\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(errors, {\n deleteError: action.payload,\n failedInstrument: action.meta.instrumentId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: InstrumentStatusState = DEFAULT_STATE.statuses,\n action: InstrumentAction,\n): InstrumentStatusState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n return objectMerge(statuses, {\n isDeleting: true,\n deletingInstrument: action.meta.instrumentId,\n });\n\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case InstrumentActionType.DeleteInstrumentSucceeded:\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(statuses, {\n isDeleting: false,\n deletingInstrument: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { AmazonPayRemoteCheckout } from './methods';\n\nexport default interface RemoteCheckoutState {\n data: RemoteCheckoutStateData;\n}\n\nexport interface RemoteCheckoutStateData {\n amazon?: AmazonPayRemoteCheckout;\n}\n\nexport const DEFAULT_STATE: RemoteCheckoutState = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport RemoteCheckout from './remote-checkout';\nimport { RemoteCheckoutAction, RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default function remoteCheckoutReducer(\n state: RemoteCheckoutState = DEFAULT_STATE,\n action: RemoteCheckoutAction,\n): RemoteCheckoutState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: RemoteCheckout, action: RemoteCheckoutAction): RemoteCheckout {\n switch (action.type) {\n case RemoteCheckoutActionType.InitializeRemoteBillingSucceeded:\n return objectSet(data, 'billing' as any, action.payload && action.payload.billing);\n\n case RemoteCheckoutActionType.InitializeRemoteShippingSucceeded:\n return objectSet(data, 'shipping' as any, action.payload && action.payload.shipping);\n\n case RemoteCheckoutActionType.LoadRemoteSettingsSucceeded:\n return objectSet(data, 'settings', action.payload);\n\n case RemoteCheckoutActionType.UpdateRemoteCheckout:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import Consignment from './consignment';\n\nexport default interface ConsignmentState {\n data?: Consignment[];\n errors: ConsignmentErrorsState;\n statuses: ConsignmentStatusesState;\n}\n\nexport interface ConsignmentErrorsState {\n loadError?: Error;\n loadShippingOptionsError?: Error;\n createError?: Error;\n updateError: { [key: string]: Error | undefined };\n deleteError: { [key: string]: Error | undefined };\n updateShippingOptionError: { [key: string]: Error | undefined };\n}\n\nexport interface ConsignmentStatusesState {\n isLoading?: boolean;\n isLoadingShippingOptions?: boolean;\n isCreating?: boolean;\n isUpdating: { [key: string]: boolean };\n isDeleting: { [key: string]: boolean };\n isUpdatingShippingOption: { [key: string]: boolean };\n}\n\nexport const DEFAULT_STATE: ConsignmentState = {\n errors: {\n updateShippingOptionError: {},\n updateError: {},\n deleteError: {},\n },\n statuses: {\n isUpdating: {},\n isUpdatingShippingOption: {},\n isDeleting: {},\n },\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType } from '../coupon';\nimport { CustomerAction, CustomerActionType } from '../customer';\n\nimport Consignment from './consignment';\nimport { ConsignmentAction, ConsignmentActionType } from './consignment-actions';\nimport ConsignmentState, {\n ConsignmentErrorsState,\n ConsignmentStatusesState,\n DEFAULT_STATE,\n} from './consignment-state';\n\nexport default function consignmentReducer(\n state: ConsignmentState = DEFAULT_STATE,\n action: Action,\n): ConsignmentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Consignment[] | undefined,\n action: ConsignmentAction | CheckoutAction | CouponAction | CustomerAction,\n): Consignment[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n return arrayReplace(data, action.payload && action.payload.consignments);\n\n case CustomerActionType.SignOutCustomerSucceeded:\n return arrayReplace(data, []);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConsignmentErrorsState = DEFAULT_STATE.errors,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConsignmentStatusesState = DEFAULT_STATE.statuses,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(statuses, 'isLoadingShippingOptions', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(statuses, 'isLoadingShippingOptions', false);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(statuses, 'isCreating', false);\n\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n default:\n return statuses;\n }\n}\n","/**\n * Takes a nested object and flattens it.\n */\nexport default function objectFlatten(\n object: { [key: string]: any },\n parent?: string,\n): { [key: string]: any } {\n const flattened: { [key: string]: any } = {};\n\n Object.keys(object).forEach((key: string) => {\n const value = object[key];\n const keyString = parent ? `${parent}.${key}` : key;\n\n if (typeof value === 'object') {\n Object.assign(flattened, objectFlatten(value, keyString));\n } else {\n flattened[keyString] = value;\n }\n });\n\n return flattened;\n}\n","export default function objectWithSortedKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n const sortedKeys = keys.sort();\n\n const sortedArray = sortedKeys.reduce(\n (previous, current) => ({\n ...previous,\n [current]: object[current],\n }),\n {},\n );\n\n return sortedArray;\n}\n","import { PickupOptionQueryMap } from './pickup-option';\n\nexport default interface PickupOptionState {\n data?: PickupOptionQueryMap;\n errors: PickupOptionErrorsState;\n statuses: PickupOptionStatusesState;\n}\n\nexport interface PickupOptionErrorsState {\n loadError?: Error;\n}\n\nexport interface PickupOptionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: PickupOptionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectFlatten, objectSet, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionQueryMap } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionState, {\n DEFAULT_STATE,\n PickupOptionErrorsState,\n PickupOptionStatusesState,\n} from './pickup-option-state';\n\nexport default function pickupOptionReducer(\n state: PickupOptionState = DEFAULT_STATE,\n action: Action,\n): PickupOptionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PickupOptionQueryMap | undefined,\n action: LoadPickupOptionsAction,\n): PickupOptionQueryMap | undefined {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n if (action.meta) {\n const optionQuery = {\n consignmentId: action.meta.consignmentId,\n searchArea: action.meta.searchArea,\n };\n const flattenedMeta = objectFlatten(optionQuery);\n const sortedflattenedMeta = objectWithSortedKeys(flattenedMeta);\n const keyString = btoa(`${JSON.stringify(sortedflattenedMeta)}`);\n\n return objectSet(data, keyString, action.payload);\n }\n\n break;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: PickupOptionErrorsState = DEFAULT_STATE.errors, action: Action) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PickupOptionStatusesState = DEFAULT_STATE.statuses,\n action: Action,\n) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Country } from '../geography';\n\nexport default interface ShippingCountryState {\n data?: Country[];\n errors: ShippingCountryErrorsState;\n statuses: ShippingCountryStatusesState;\n}\n\nexport interface ShippingCountryErrorsState {\n loadError?: Error;\n}\n\nexport interface ShippingCountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ShippingCountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { Country } from '../geography';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryState, {\n DEFAULT_STATE,\n ShippingCountryErrorsState,\n ShippingCountryStatusesState,\n} from './shipping-country-state';\n\nexport default function shippingCountryReducer(\n state: ShippingCountryState = DEFAULT_STATE,\n action: Action,\n): ShippingCountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadShippingCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ShippingCountryErrorsState = DEFAULT_STATE.errors,\n action: LoadShippingCountriesAction,\n): ShippingCountryErrorsState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingCountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadShippingCountriesAction,\n): ShippingCountryStatusesState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","export default interface ShippingStrategyState {\n data: ShippingStrategyDataState;\n errors: ShippingStrategyErrorsState;\n statuses: ShippingStrategyStatusesState;\n}\n\nexport interface ShippingStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface ShippingStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n updateAddressError?: Error;\n updateAddressMethodId?: string;\n selectOptionError?: Error;\n selectOptionMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface ShippingStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isUpdatingAddress?: boolean;\n isSelectingOption?: boolean;\n updateAddressMethodId?: string;\n selectOptionMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: ShippingStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { ShippingStrategyAction, ShippingStrategyActionType } from './shipping-strategy-actions';\nimport ShippingStrategyState, {\n DEFAULT_STATE,\n ShippingStrategyDataState,\n ShippingStrategyErrorsState,\n ShippingStrategyStatusesState,\n} from './shipping-strategy-state';\n\nexport default function shippingStrategyReducer(\n state: ShippingStrategyState = DEFAULT_STATE,\n action: Action,\n): ShippingStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: ShippingStrategyDataState = DEFAULT_STATE.data,\n action: ShippingStrategyAction,\n): ShippingStrategyDataState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ShippingStrategyErrorsState = DEFAULT_STATE.errors,\n action: ShippingStrategyAction,\n): ShippingStrategyErrorsState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(errors, {\n updateAddressError: undefined,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n return objectMerge(errors, {\n updateAddressError: action.payload,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(errors, {\n selectOptionError: undefined,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n return objectMerge(errors, {\n selectOptionError: action.payload,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n case ShippingStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingStrategyStatusesState = DEFAULT_STATE.statuses,\n action: ShippingStrategyAction,\n): ShippingStrategyStatusesState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n return objectMerge(statuses, {\n isUpdatingAddress: true,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(statuses, {\n isUpdatingAddress: false,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n return objectMerge(statuses, {\n isSelectingOption: true,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(statuses, {\n isSelectingOption: false,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFinished:\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { SignInEmail } from './signin-email';\n\nexport default interface SignInEmailState {\n data?: SignInEmail;\n errors: SignInEmailErrorsState;\n statuses: SignInEmailStatusesState;\n}\n\nexport interface SignInEmailErrorsState {\n sendError?: Error;\n}\n\nexport interface SignInEmailStatusesState {\n isSending?: boolean;\n}\n\nexport const DEFAULT_STATE: SignInEmailState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { SignInEmail } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailState, {\n DEFAULT_STATE,\n SignInEmailErrorsState,\n SignInEmailStatusesState,\n} from './signin-email-state';\n\nexport default function signInEmailReducer(\n state: SignInEmailState = DEFAULT_STATE,\n action: Action,\n): SignInEmailState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: SignInEmail | undefined,\n action: SendSignInEmailAction,\n): SignInEmail | undefined {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: SignInEmailErrorsState = DEFAULT_STATE.errors,\n action: SendSignInEmailAction,\n): SignInEmailErrorsState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(errors, 'sendError', undefined);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n return objectSet(errors, 'sendError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SignInEmailStatusesState = DEFAULT_STATE.statuses,\n action: SendSignInEmailAction,\n): SignInEmailStatusesState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n return objectSet(statuses, 'isSending', true);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(statuses, 'isSending', false);\n\n default:\n return statuses;\n }\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditState, {\n StoreCreditErrorsState,\n StoreCreditStatusesState,\n} from './store-credit-state';\n\nconst DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n\nexport default function storeCreditReducer(\n state: StoreCreditState = DEFAULT_STATE,\n action: Action,\n): StoreCreditState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: StoreCreditErrorsState = DEFAULT_STATE.errors,\n action: StoreCreditAction,\n): StoreCreditErrorsState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n return objectSet(errors, 'applyError', undefined);\n\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(errors, 'applyError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: StoreCreditStatusesState = DEFAULT_STATE.statuses,\n action: StoreCreditAction,\n): StoreCreditStatusesState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n return objectSet(statuses, 'isApplying', true);\n\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(statuses, 'isApplying', false);\n\n default:\n return statuses;\n }\n}\n","export default interface SubscriptionsState {\n errors: SubscriptionsErrorsState;\n statuses: SubscriptionsStatusesState;\n}\n\nexport interface SubscriptionsErrorsState {\n updateError?: Error;\n}\n\nexport interface SubscriptionsStatusesState {\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: SubscriptionsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport SubscriptionsState, {\n DEFAULT_STATE,\n SubscriptionsErrorsState,\n SubscriptionsStatusesState,\n} from './subscriptions-state';\n\nexport default function subscriptionsReducer(\n state: SubscriptionsState = DEFAULT_STATE,\n action: Action,\n): SubscriptionsState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: SubscriptionsErrorsState = DEFAULT_STATE.errors,\n action: UpdateSubscriptionsAction,\n): SubscriptionsErrorsState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SubscriptionsStatusesState = DEFAULT_STATE.statuses,\n action: UpdateSubscriptionsAction,\n): SubscriptionsStatusesState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport Checkout from './checkout';\n\nexport default interface CheckoutState {\n data?: CheckoutDataState;\n errors: CheckoutErrorsState;\n statuses: CheckoutStatusesState;\n}\n\nexport type CheckoutDataState = Omit<\n Checkout,\n 'billingAddress' | 'cart' | 'consignments' | 'coupons' | 'giftCertificates'\n>;\n\nexport interface CheckoutErrorsState {\n loadError?: Error;\n updateError?: Error;\n}\n\nexport interface CheckoutStatusesState {\n isExecutingSpamCheck?: boolean;\n isLoading?: boolean;\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\nimport { SpamProtectionAction, SpamProtectionActionType } from '../spam-protection';\nimport { StoreCreditAction, StoreCreditActionType } from '../store-credit';\n\nimport { CheckoutAction, CheckoutActionType } from './checkout-actions';\nimport CheckoutState, {\n CheckoutDataState,\n CheckoutErrorsState,\n CheckoutStatusesState,\n DEFAULT_STATE,\n} from './checkout-state';\n\nexport default function checkoutReducer(\n state: CheckoutState = DEFAULT_STATE,\n action: Action,\n): CheckoutState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutDataState | undefined,\n action:\n | CheckoutAction\n | BillingAddressAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction\n | OrderAction\n | SpamProtectionAction\n | StoreCreditAction,\n): CheckoutDataState | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case SpamProtectionActionType.VerifyCheckoutSucceeded:\n return objectMerge(\n data,\n omit(action.payload, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\n\n case OrderActionType.SubmitOrderSucceeded:\n return objectSet(data, 'orderId', action.payload && action.payload.order.orderId);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CheckoutErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | OrderAction,\n): CheckoutErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | OrderAction | SpamProtectionAction,\n): CheckoutStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case SpamProtectionActionType.ExecuteRequested:\n return objectSet(statuses, 'isExecutingSpamCheck', true);\n\n case SpamProtectionActionType.ExecuteFailed:\n case SpamProtectionActionType.ExecuteSucceeded:\n return objectSet(statuses, 'isExecutingSpamCheck', false);\n\n default:\n return statuses;\n }\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import { deepFreeze } from '@bigcommerce/data-store';\n\n// tslint:disable-next-line:ban-types\ntype FunctionProperties = { [K in keyof T]: T[K] extends Function ? T[K] : never };\n\nexport default function createFreezeProxy(target: T): T {\n return createProxy(\n target,\n (target, name) =>\n (...args: any[]) =>\n deepFreeze(target[name].call(target, ...args)),\n );\n}\n\nexport function createFreezeProxies(\n map: TMap,\n): TMap {\n return Object.keys(map).reduce((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {} as { [key: string]: T }) as TMap;\n}\n\nfunction createProxy(\n target: T,\n trap: (target: FunctionProperties, name: keyof FunctionProperties, proxy: T) => any,\n): T {\n const proxy = Object.create(target);\n\n traversePrototypeOf(target, (prototype) => {\n Object.getOwnPropertyNames(prototype).forEach((name) => {\n if (\n name === 'constructor' ||\n typeof proxy[name] !== 'function' ||\n name.charAt(0) === '_'\n ) {\n return;\n }\n\n proxy[name] = trap(target as FunctionProperties, name as keyof T, proxy);\n });\n });\n\n return proxy;\n}\n\nfunction traversePrototypeOf(target: object, iteratee: (prototype: object) => void): void {\n let prototype = Object.getPrototypeOf(target);\n\n while (prototype) {\n iteratee(prototype);\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n","import PaymentInstrument from './instrument';\n\ninterface SupportedInstruments {\n [key: string]: Pick;\n}\n\nconst supportedInstruments: SupportedInstruments = {\n 'mollie.credit_card': {\n provider: 'mollie',\n method: 'credit_card',\n },\n 'adyenv2.scheme': {\n provider: 'adyenv2',\n method: 'scheme',\n },\n 'adyenv3.scheme': {\n provider: 'adyenv3',\n method: 'scheme',\n },\n 'adyenv2.bcmc': {\n provider: 'adyenv2',\n method: 'bcmc',\n },\n 'adyenv2.ideal': {\n provider: 'adyenv2',\n method: 'ideal',\n },\n 'adyenv2.sepadirectdebit': {\n provider: 'adyenv2',\n method: 'sepadirectdebit',\n },\n 'adyenv2.directEbanking': {\n provider: 'adyenv2',\n method: 'directEbanking',\n },\n 'adyenv2.giropay': {\n provider: 'adyenv2',\n method: 'giropay',\n },\n barclays: {\n provider: 'barclays',\n method: 'credit_card',\n },\n braintree: {\n provider: 'braintree',\n method: 'credit_card',\n },\n braintreepaypal: {\n provider: 'braintree',\n method: 'paypal',\n },\n braintreeach: {\n provider: 'braintree',\n method: 'ach',\n },\n authorizenet: {\n provider: 'authorizenet',\n method: 'credit_card',\n },\n elavon: {\n provider: 'elavon',\n method: 'credit_card',\n },\n checkoutcom: {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.credit_card': {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.card': {\n provider: 'checkoutcom',\n method: 'card',\n },\n sagepay: {\n provider: 'sagepay',\n method: 'credit_card',\n },\n stripe: {\n provider: 'stripe',\n method: 'credit_card',\n },\n 'stripev3.card': {\n provider: 'stripev3',\n method: 'card',\n },\n 'stripeupe.card': {\n provider: 'stripeupe',\n method: 'card',\n },\n cybersource: {\n provider: 'cybersource',\n method: 'credit_card',\n },\n cybersourcev2: {\n provider: 'cybersourcev2',\n method: 'credit_card',\n },\n bnz: {\n provider: 'bnz',\n method: 'credit_card',\n },\n converge: {\n provider: 'converge',\n method: 'credit_card',\n },\n bluesnapv2: {\n provider: 'bluesnapv2',\n method: 'credit_card',\n },\n 'bluesnapdirect.credit_card': {\n provider: 'bluesnapdirect',\n method: 'credit_card',\n },\n 'bluesnapdirect.ecp': {\n provider: 'bluesnapdirect',\n method: 'ecp',\n },\n 'bluesnapdirect.sepa_direct_debit': {\n provider: 'bluesnapdirect',\n method: 'sepa_direct_debit',\n },\n orbital: {\n provider: 'orbital',\n method: 'credit_card',\n },\n paymetric: {\n provider: 'paymetric',\n method: 'credit_card',\n },\n bolt: {\n provider: 'bolt',\n method: 'credit_card',\n },\n 'barclaycard.credit_card': {\n provider: 'barclaycard',\n method: 'credit_card',\n },\n digitalriver: {\n provider: 'digitalriver',\n method: 'credit_card',\n },\n moneris: {\n provider: 'moneris',\n method: 'credit_card',\n },\n cba_mpgs: {\n provider: 'cba_mpgs',\n method: 'credit_card',\n },\n worldpayaccess: {\n provider: 'worldpayaccess',\n method: 'credit_card',\n },\n squarev2: {\n provider: 'squarev2',\n method: 'credit_card',\n },\n paypalcommercecreditcards: {\n provider: 'paypalcommerce',\n method: 'credit_card',\n },\n paypalcommerce: {\n provider: 'paypalcommerce',\n method: 'paypal',\n },\n tdonlinemart: {\n provider: 'tdonlinemart',\n method: 'credit_card',\n },\n};\n\nexport default supportedInstruments;\n","import { identity, isEqual, pickBy } from 'lodash';\n\nimport Address from './address';\n\nexport default function isAddressEqual(\n addressA: Partial
,\n addressB: Partial
,\n): boolean {\n return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial
): Partial
{\n return pickBy(\n {\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n address1: address.address1,\n address2: address.address2,\n city: address.city,\n stateOrProvince: address.stateOrProvince,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n phone: address.phone,\n customFields: address.customFields,\n },\n identity,\n );\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nexport default interface StoreCreditState {\n errors: StoreCreditErrorsState;\n statuses: StoreCreditStatusesState;\n}\n\nexport interface StoreCreditErrorsState {\n applyError?: RequestError;\n}\n\nexport interface StoreCreditStatusesState {\n isApplying?: boolean;\n}\n\nexport const DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n","import { createBillingAddressSelectorFactory } from '../billing';\nimport { createCartSelectorFactory } from '../cart';\nimport { createCheckoutButtonSelectorFactory } from '../checkout-buttons';\nimport { createFreezeProxies } from '../common/utility';\nimport { createConfigSelectorFactory } from '../config';\nimport { createCouponSelectorFactory, createGiftCertificateSelectorFactory } from '../coupon';\nimport { createCustomerSelectorFactory, createCustomerStrategySelectorFactory } from '../customer';\nimport { createExtensionSelectorFactory } from '../extension';\nimport { createFormSelectorFactory } from '../form';\nimport { createCountrySelectorFactory } from '../geography';\nimport { createOrderSelectorFactory } from '../order';\nimport { createOrderBillingAddressSelectorFactory } from '../order-billing-address';\nimport {\n createPaymentMethodSelectorFactory,\n createPaymentSelectorFactory,\n createPaymentStrategySelectorFactory,\n} from '../payment';\nimport { createPaymentProviderCustomerSelectorFactory } from '../payment-provider-customer';\nimport { createInstrumentSelectorFactory } from '../payment/instrument';\nimport { createRemoteCheckoutSelectorFactory } from '../remote-checkout';\nimport {\n createConsignmentSelectorFactory,\n createPickupOptionSelectorFactory,\n createShippingAddressSelectorFactory,\n createShippingCountrySelectorFactory,\n createShippingStrategySelectorFactory,\n} from '../shipping';\nimport { createSignInEmailSelectorFactory } from '../signin-email';\nimport { createStoreCreditSelectorFactory } from '../store-credit';\nimport { createSubscriptionsSelectorFactory } from '../subscription';\n\nimport { createCheckoutSelectorFactory } from './checkout-selector';\nimport { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type InternalCheckoutSelectorsFactory = (\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n) => InternalCheckoutSelectors;\n\nexport function createInternalCheckoutSelectorsFactory(): InternalCheckoutSelectorsFactory {\n const createBillingAddressSelector = createBillingAddressSelectorFactory();\n const createCartSelector = createCartSelectorFactory();\n const createCheckoutButtonSelector = createCheckoutButtonSelectorFactory();\n const createConfigSelector = createConfigSelectorFactory();\n const createCountrySelector = createCountrySelectorFactory();\n const createCouponSelector = createCouponSelectorFactory();\n const createCustomerSelector = createCustomerSelectorFactory();\n const createCustomerStrategySelector = createCustomerStrategySelectorFactory();\n const createGiftCertificateSelector = createGiftCertificateSelectorFactory();\n const createInstrumentSelector = createInstrumentSelectorFactory();\n const createFormSelector = createFormSelectorFactory();\n const createPaymentMethodSelector = createPaymentMethodSelectorFactory();\n const createPaymentStrategySelector = createPaymentStrategySelectorFactory();\n const createPickupOptionSelector = createPickupOptionSelectorFactory();\n const createPaymentProviderCustomerSelector = createPaymentProviderCustomerSelectorFactory();\n const createRemoteCheckoutSelector = createRemoteCheckoutSelectorFactory();\n const createShippingAddressSelector = createShippingAddressSelectorFactory();\n const createShippingCountrySelector = createShippingCountrySelectorFactory();\n const createShippingStrategySelector = createShippingStrategySelectorFactory();\n const createConsignmentSelector = createConsignmentSelectorFactory();\n const createCheckoutSelector = createCheckoutSelectorFactory();\n const createOrderSelector = createOrderSelectorFactory();\n const createOrderBillingAddressSelector = createOrderBillingAddressSelectorFactory();\n const createPaymentSelector = createPaymentSelectorFactory();\n const createStoreCreditSelector = createStoreCreditSelectorFactory();\n const createSubscriptionsSelector = createSubscriptionsSelectorFactory();\n const createSignInEmailSelector = createSignInEmailSelectorFactory();\n const createExtensionSelector = createExtensionSelectorFactory();\n\n return (state, options = {}) => {\n const billingAddress = createBillingAddressSelector(state.billingAddress);\n const cart = createCartSelector(state.cart);\n const checkoutButton = createCheckoutButtonSelector(state.checkoutButton);\n const countries = createCountrySelector(state.countries);\n const coupons = createCouponSelector(state.coupons);\n const customer = createCustomerSelector(state.customer);\n const customerStrategies = createCustomerStrategySelector(state.customerStrategies);\n const extensions = createExtensionSelector(state.extensions);\n const form = createFormSelector(state.formFields);\n const giftCertificates = createGiftCertificateSelector(state.giftCertificates);\n const instruments = createInstrumentSelector(state.instruments);\n const orderBillingAddress = createOrderBillingAddressSelector(state.orderBillingAddress);\n const paymentMethods = createPaymentMethodSelector(state.paymentMethods);\n const paymentProviderCustomer = createPaymentProviderCustomerSelector(\n state.paymentProviderCustomer,\n );\n const paymentStrategies = createPaymentStrategySelector(state.paymentStrategies);\n const pickupOptions = createPickupOptionSelector(state.pickupOptions);\n const remoteCheckout = createRemoteCheckoutSelector(state.remoteCheckout);\n const shippingAddress = createShippingAddressSelector(state.consignments);\n const shippingCountries = createShippingCountrySelector(state.shippingCountries);\n const shippingStrategies = createShippingStrategySelector(state.shippingStrategies);\n const subscriptions = createSubscriptionsSelector(state.subscriptions);\n const storeCredit = createStoreCreditSelector(state.storeCredit);\n const signInEmail = createSignInEmailSelector(state.signInEmail);\n\n // Compose selectors\n const consignments = createConsignmentSelector(state.consignments, cart);\n const checkout = createCheckoutSelector(\n state.checkout,\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n );\n const order = createOrderSelector(state.order, orderBillingAddress, coupons);\n const payment = createPaymentSelector(checkout, order);\n const config = createConfigSelector(state.config, state.formFields);\n\n const selectors = {\n billingAddress,\n cart,\n checkout,\n checkoutButton,\n config,\n consignments,\n countries,\n coupons,\n customer,\n customerStrategies,\n extensions,\n form,\n giftCertificates,\n instruments,\n order,\n orderBillingAddress,\n payment,\n paymentMethods,\n paymentProviderCustomer,\n paymentStrategies,\n pickupOptions,\n remoteCheckout,\n shippingAddress,\n shippingCountries,\n shippingStrategies,\n signInEmail,\n subscriptions,\n storeCredit,\n };\n\n return options.shouldWarnMutation ? createFreezeProxies(selectors) : selectors;\n };\n}\n\nexport default function createInternalCheckoutSelectors(\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n): InternalCheckoutSelectors {\n return createInternalCheckoutSelectorsFactory()(state, options);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport BillingAddress from './billing-address';\nimport BillingAddressState, { DEFAULT_STATE } from './billing-address-state';\n\nexport default interface BillingAddressSelector {\n getBillingAddress(): BillingAddress | undefined;\n getBillingAddressOrThrow(): BillingAddress;\n getUpdateError(): Error | undefined;\n getContinueAsGuestError(): Error | undefined;\n getLoadError(): Error | undefined;\n isUpdating(): boolean;\n isContinuingAsGuest(): boolean;\n isLoading(): boolean;\n}\n\nexport type BillingAddressSelectorFactory = (state: BillingAddressState) => BillingAddressSelector;\n\nexport function createBillingAddressSelectorFactory(): BillingAddressSelectorFactory {\n const getBillingAddress = createSelector(\n (state: BillingAddressState) => state.data,\n (data) => () => data,\n );\n\n const getBillingAddressOrThrow = createSelector(\n getBillingAddress,\n (getBillingAddress) => () => {\n return guard(\n getBillingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingBillingAddress),\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: BillingAddressState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const getContinueAsGuestError = createSelector(\n (state: BillingAddressState) => state.errors.continueAsGuestError,\n (error) => () => error,\n );\n\n const getLoadError = createSelector(\n (state: BillingAddressState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: BillingAddressState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n const isContinuingAsGuest = createSelector(\n (state: BillingAddressState) => !!state.statuses.isContinuingAsGuest,\n (status) => () => status,\n );\n\n const isLoading = createSelector(\n (state: BillingAddressState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: BillingAddressState = DEFAULT_STATE): BillingAddressSelector => {\n return {\n getBillingAddress: getBillingAddress(state),\n getBillingAddressOrThrow: getBillingAddressOrThrow(state),\n getUpdateError: getUpdateError(state),\n getContinueAsGuestError: getContinueAsGuestError(state),\n getLoadError: getLoadError(state),\n isUpdating: isUpdating(state),\n isContinuingAsGuest: isContinuingAsGuest(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoize, memoizeOne } from '@bigcommerce/memoize';\nimport { find, some, values } from 'lodash';\n\nimport { createSelector } from '../common/selector';\n\nimport CheckoutButtonState, { DEFAULT_STATE } from './checkout-button-state';\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonSelector {\n getState(): CheckoutButtonState;\n isInitializing(methodId?: CheckoutButtonMethodType): boolean;\n isInitialized(methodId: CheckoutButtonMethodType, containerId?: string): boolean;\n isDeinitializing(methodId?: CheckoutButtonMethodType): boolean;\n getInitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n getDeinitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n}\n\nexport type CheckoutButtonSelectorFactory = (state: CheckoutButtonState) => CheckoutButtonSelector;\n\nexport function createCheckoutButtonSelectorFactory(): CheckoutButtonSelectorFactory {\n const getState = createSelector(\n (state: CheckoutButtonState) => state,\n (state) => () => state,\n );\n\n const isInitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isInitializing) === true;\n }\n\n return some(statuses, { isInitializing: true });\n }),\n );\n\n const isInitialized = createSelector(\n (state: CheckoutButtonState) => state.data,\n (data) =>\n memoize((methodId: CheckoutButtonMethodType, containerId?: string) => {\n const method = data[methodId];\n\n if (!method) {\n return false;\n }\n\n if (!containerId) {\n return some(\n method.initializedContainers,\n (isInitialized) => isInitialized === true,\n );\n }\n\n return method.initializedContainers[containerId] === true;\n }),\n );\n\n const isDeinitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isDeinitializing) === true;\n }\n\n return some(statuses, { isDeinitializing: true });\n }),\n );\n\n const getInitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.initializeError));\n\n return method && method.initializeError;\n }),\n );\n\n const getDeinitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.deinitializeError));\n\n return method && method.deinitializeError;\n }),\n );\n\n return memoizeOne((state: CheckoutButtonState = DEFAULT_STATE): CheckoutButtonSelector => {\n return {\n getState: getState(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isDeinitializing: isDeinitializing(state),\n getInitializeError: getInitializeError(state),\n getDeinitializeError: getDeinitializeError(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport Coupon from './coupon';\nimport CouponState, { DEFAULT_STATE } from './coupon-state';\n\nexport default interface CouponSelector {\n getCoupons(): Coupon[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type CouponSelectorFactory = (state: CouponState) => CouponSelector;\n\nexport function createCouponSelectorFactory(): CouponSelectorFactory {\n const getCoupons = createSelector(\n (state: CouponState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: CouponState) => state.errors.removeCouponError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: CouponState) => state.errors.applyCouponError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: CouponState) => !!state.statuses.isApplyingCoupon,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: CouponState) => !!state.statuses.isRemovingCoupon,\n (status) => () => status,\n );\n\n return memoizeOne((state: CouponState = DEFAULT_STATE): CouponSelector => {\n return {\n getCoupons: getCoupons(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Customer from './customer';\nimport CustomerState, { DEFAULT_STATE } from './customer-state';\n\nexport default interface CustomerSelector {\n getCustomer(): Customer | undefined;\n getCustomerOrThrow(): Customer;\n getCreateAccountError(): Error | undefined;\n isCreatingCustomerAccount(): boolean;\n getCreateAddressError(): Error | undefined;\n isCreatingCustomerAddress(): boolean;\n}\n\nexport type CustomerSelectorFactory = (state: CustomerState) => CustomerSelector;\n\nexport function createCustomerSelectorFactory(): CustomerSelectorFactory {\n const getCustomer = createSelector(\n (state: CustomerState) => state.data,\n (customer) => () => customer,\n );\n\n const getCustomerOrThrow = createSelector(getCustomer, (getCustomer) => () => {\n return guard(\n getCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingCustomer),\n );\n });\n\n const getCreateAccountError = createSelector(\n (state: CustomerState) => state.errors.createError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAccount = createSelector(\n (state: CustomerState) => !!state.statuses.isCreating,\n (status) => () => status,\n );\n\n const getCreateAddressError = createSelector(\n (state: CustomerState) => state.errors.createAddressError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAddress = createSelector(\n (state: CustomerState) => !!state.statuses.isCreatingAddress,\n (status) => () => status,\n );\n\n return memoizeOne((state: CustomerState = DEFAULT_STATE): CustomerSelector => {\n return {\n getCustomer: getCustomer(state),\n getCustomerOrThrow: getCustomerOrThrow(state),\n getCreateAccountError: getCreateAccountError(state),\n isCreatingCustomerAccount: isCreatingCustomerAccount(state),\n getCreateAddressError: getCreateAddressError(state),\n isCreatingCustomerAddress: isCreatingCustomerAddress(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport PaymentProviderCustomerState, { DEFAULT_STATE } from './payment-provider-customer-state';\n\nexport default interface PaymentProviderCustomerSelector {\n getPaymentProviderCustomer(): PaymentProviderCustomer | undefined;\n getPaymentProviderCustomerOrThrow(): PaymentProviderCustomer;\n}\n\nexport type PaymentProviderCustomerSelectorFactory = (\n state: PaymentProviderCustomerState,\n) => PaymentProviderCustomerSelector;\n\nexport function createPaymentProviderCustomerSelectorFactory(): PaymentProviderCustomerSelectorFactory {\n const getPaymentProviderCustomer = createSelector(\n (state: PaymentProviderCustomerState) => state.data,\n (data) => () => data,\n );\n\n const getPaymentProviderCustomerOrThrow = createSelector(\n getPaymentProviderCustomer,\n (getPaymentProviderCustomer) => () => {\n return guard(\n getPaymentProviderCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentProviderCustomer),\n );\n },\n );\n\n return memoizeOne(\n (state: PaymentProviderCustomerState = DEFAULT_STATE): PaymentProviderCustomerSelector => {\n return {\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n getPaymentProviderCustomerOrThrow: getPaymentProviderCustomerOrThrow(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default interface RemoteCheckoutSelector {\n getCheckout(\n methodId: TMethodId,\n ): RemoteCheckoutStateData[TMethodId] | undefined;\n}\n\nexport type RemoteCheckoutSelectorFactory = (state: RemoteCheckoutState) => RemoteCheckoutSelector;\n\nexport function createRemoteCheckoutSelectorFactory(): RemoteCheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: RemoteCheckoutState) => state.data,\n (data) =>\n (methodId: TMethodId) => {\n return data[methodId];\n },\n );\n\n return memoizeOne((state: RemoteCheckoutState = DEFAULT_STATE): RemoteCheckoutSelector => {\n return {\n getCheckout: getCheckout(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { Address } from '../address';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\n\nexport default interface ShippingAddressSelector {\n getShippingAddress(): Address | undefined;\n getShippingAddressOrThrow(): Address;\n getShippingAddresses(): Address[];\n getShippingAddressesOrThrow(): Address[];\n}\n\nexport type ShippingAddressSelectorFactory = (state: ConsignmentState) => ShippingAddressSelector;\n\nexport function createShippingAddressSelectorFactory(): ShippingAddressSelectorFactory {\n const getShippingAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.shippingAddress;\n },\n );\n\n const getShippingAddressOrThrow = createSelector(\n getShippingAddress,\n (getShippingAddress) => () => {\n return guard(\n getShippingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n const getShippingAddresses = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignments = consignments?.filter(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignments\n ? shippingConsignments.map((consignment) => consignment.shippingAddress)\n : [];\n },\n );\n\n const getShippingAddressesOrThrow = createSelector(\n getShippingAddresses,\n (getShippingAddresses) => () => {\n return guard(\n getShippingAddresses(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n return memoizeOne((state: ConsignmentState = DEFAULT_STATE): ShippingAddressSelector => {\n return {\n getShippingAddress: getShippingAddress(state),\n getShippingAddressOrThrow: getShippingAddressOrThrow(state),\n getShippingAddresses: getShippingAddresses(state),\n getShippingAddressesOrThrow: getShippingAddressesOrThrow(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default interface OrderBillingAddressSelector {\n getOrderBillingAddress(): OrderBillingAddress | undefined;\n}\n\nexport type OrderBillingAddressSelectorFactory = (\n state: OrderBillingAddressState,\n) => OrderBillingAddressSelector;\n\nexport function createOrderBillingAddressSelectorFactory(): OrderBillingAddressSelectorFactory {\n const getOrderBillingAddress = createSelector(\n (state: OrderBillingAddressState) => state.data,\n (data) => () => data,\n );\n\n return memoizeOne(\n (state: OrderBillingAddressState = DEFAULT_STATE): OrderBillingAddressSelector => {\n return {\n getOrderBillingAddress: getOrderBillingAddress(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { CheckoutSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { GatewayOrderPayment, OrderSelector } from '../order';\n\nimport PaymentMethod from './payment-method';\nimport { HOSTED } from './payment-method-types';\nimport { ACKNOWLEDGE, FINALIZE } from './payment-status-types';\n\nexport default interface PaymentSelector {\n getPaymentId(): { providerId: string; gatewayId?: string } | undefined;\n getPaymentIdOrThrow(): { providerId: string; gatewayId?: string };\n getPaymentStatus(): string | undefined;\n getPaymentStatusOrThrow(): string;\n getPaymentToken(): string | undefined;\n getPaymentTokenOrThrow(): string;\n getPaymentRedirectUrl(): string | undefined;\n getPaymentRedirectUrlOrThrow(): string;\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n isPaymentDataSubmitted(paymentMethod?: PaymentMethod): boolean;\n}\n\nexport type PaymentSelectorFactory = (\n checkout: CheckoutSelector,\n order: OrderSelector,\n) => PaymentSelector;\n\ninterface PaymentSelectorDependencies {\n checkout: CheckoutSelector;\n order: OrderSelector;\n}\n\nexport function createPaymentSelectorFactory(): PaymentSelectorFactory {\n const getInternalPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.payment;\n },\n );\n\n const getGatewayPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrder,\n (getOrder) => () => {\n const order = getOrder();\n\n return find(\n order && order.payments,\n ({ providerId }) =>\n providerId !== 'giftcertificate' && providerId !== 'storecredit',\n ) as GatewayOrderPayment;\n },\n );\n\n const getHostedPayment = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getCheckout,\n (getCheckout) => () => {\n const checkout = getCheckout();\n\n return find(\n checkout && checkout.payments,\n ({ providerType }) => providerType === HOSTED,\n );\n },\n );\n\n const getPaymentId = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.id) {\n return {\n providerId: internalPayment.id,\n gatewayId: internalPayment.gateway,\n };\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment && payment.providerId) {\n return {\n providerId: payment.providerId,\n gatewayId: payment.gatewayId,\n };\n }\n },\n );\n\n const getPaymentIdOrThrow = createSelector(getPaymentId, (getPaymentId) => () => {\n return guard(\n getPaymentId(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentId),\n );\n });\n\n const getPaymentStatus = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.status) {\n return internalPayment.status.replace('PAYMENT_STATUS_', '');\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment) {\n return payment.detail.step;\n }\n },\n );\n\n const getPaymentStatusOrThrow = createSelector(getPaymentStatus, (getPaymentStatus) => () => {\n return guard(\n getPaymentStatus(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentStatus),\n );\n });\n\n const getPaymentToken = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.token;\n },\n );\n\n const getPaymentTokenOrThrow = createSelector(getPaymentToken, (getPaymentToken) => () => {\n return guard(\n getPaymentToken(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n });\n\n const getPaymentRedirectUrl = createSelector(getInternalPayment, (getInternalPayment) => () => {\n const payment = getInternalPayment();\n\n return payment && payment.redirectUrl;\n });\n\n const getPaymentRedirectUrlOrThrow = createSelector(\n getPaymentRedirectUrl,\n (getPaymentRedirectUrl) => () => {\n return guard(\n getPaymentRedirectUrl(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentRedirectUrl),\n );\n },\n );\n\n const isPaymentDataRequired = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getOutstandingBalance,\n (getOutstandingBalance) =>\n (useStoreCredit = false) => {\n const grandTotal = getOutstandingBalance(useStoreCredit);\n\n return grandTotal ? grandTotal > 0 : false;\n },\n );\n\n const isPaymentDataSubmitted = createSelector(\n getPaymentStatus,\n (getPaymentStatus) => (paymentMethod?: PaymentMethod) => {\n if (paymentMethod && paymentMethod.nonce) {\n return true;\n }\n\n return getPaymentStatus() === ACKNOWLEDGE || getPaymentStatus() === FINALIZE;\n },\n );\n\n return memoizeOne((checkout: CheckoutSelector, order: OrderSelector): PaymentSelector => {\n return {\n getPaymentId: getPaymentId({ checkout, order }),\n getPaymentIdOrThrow: getPaymentIdOrThrow({ checkout, order }),\n getPaymentStatus: getPaymentStatus({ checkout, order }),\n getPaymentStatusOrThrow: getPaymentStatusOrThrow({ checkout, order }),\n getPaymentToken: getPaymentToken({ checkout, order }),\n getPaymentTokenOrThrow: getPaymentTokenOrThrow({ checkout, order }),\n getPaymentRedirectUrl: getPaymentRedirectUrl({ checkout, order }),\n getPaymentRedirectUrlOrThrow: getPaymentRedirectUrlOrThrow({ checkout, order }),\n isPaymentDataRequired: isPaymentDataRequired({ checkout, order }),\n isPaymentDataSubmitted: isPaymentDataSubmitted({ checkout, order }),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { SignInEmail } from './signin-email';\nimport SignInEmailState, { DEFAULT_STATE } from './signin-email-state';\n\nexport default interface SignInEmailSelector {\n getEmail(): SignInEmail | undefined;\n getSendError(): Error | undefined;\n isSending(): boolean;\n}\n\nexport type SignInEmailSelectorFactory = (state: SignInEmailState) => SignInEmailSelector;\n\nexport function createSignInEmailSelectorFactory(): SignInEmailSelectorFactory {\n const getEmail = createSelector(\n (state: SignInEmailState) => state.data,\n (signInEmail) => () => signInEmail,\n );\n\n const getSendError = createSelector(\n (state: SignInEmailState) => state.errors.sendError,\n (error) => () => error,\n );\n\n const isSending = createSelector(\n (state: SignInEmailState) => !!state.statuses.isSending,\n (status) => () => status,\n );\n\n return memoizeOne((state: SignInEmailState = DEFAULT_STATE): SignInEmailSelector => {\n return {\n getEmail: getEmail(state),\n getSendError: getSendError(state),\n isSending: isSending(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Cart from './cart';\nimport CartState, { DEFAULT_STATE } from './cart-state';\n\nexport default interface CartSelector {\n getCart(): Cart | undefined;\n getCartOrThrow(): Cart;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CartSelectorFactory = (state: CartState) => CartSelector;\n\nexport function createCartSelectorFactory() {\n const getCart = createSelector(\n (state: CartState) => state.data,\n (cart) => () => cart,\n );\n\n const getCartOrThrow = createSelector(getCart, (getCart) => () => {\n return guard(getCart(), () => new MissingDataError(MissingDataErrorType.MissingCart));\n });\n\n const getLoadError = createSelector(\n (state: CartState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CartState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CartState = DEFAULT_STATE): CartSelector => {\n return {\n getCart: getCart(state),\n getCartOrThrow: getCartOrThrow(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { FormFieldsState } from '../form';\n\nimport Config, { ContextConfig, FlashMessage, FlashMessageType, StoreConfig } from './config';\nimport ConfigState, { DEFAULT_STATE } from './config-state';\n\nexport default interface ConfigSelector {\n getConfig(): Config | undefined;\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n getStoreConfig(): StoreConfig | undefined;\n getStoreConfigOrThrow(): StoreConfig;\n getContextConfig(): ContextConfig | undefined;\n getExternalSource(): string | undefined;\n getHost(): string | undefined;\n getLocale(): string | undefined;\n getVariantIdentificationToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ConfigSelectorFactory = (\n state: ConfigState,\n formState: FormFieldsState,\n) => ConfigSelector;\n\ninterface ConfigSelectorDependencies {\n formState: FormFieldsState;\n}\n\nexport function createConfigSelectorFactory(): ConfigSelectorFactory {\n const getConfig = createSelector(\n (state: ConfigState) => state.data,\n (data) => () => data,\n );\n\n const getFlashMessages = createSelector(\n (state: ConfigState) => state.data,\n (data) => (filterType?: FlashMessageType) => {\n if (!data) {\n return;\n }\n\n const { flashMessages } = data.context;\n\n if (!flashMessages) {\n return;\n }\n\n return filterType !== undefined\n ? flashMessages.filter(({ type }) => filterType === type)\n : flashMessages;\n },\n );\n\n const getStoreConfig = createSelector(\n (state: ConfigState) => state.data,\n (_: ConfigState, { formState }: ConfigSelectorDependencies) => formState && formState.data,\n (data, formFields) => () =>\n data && formFields\n ? {\n ...data.storeConfig,\n formFields,\n }\n : undefined,\n );\n\n const getStoreConfigOrThrow = createSelector(getStoreConfig, (getStoreConfig) => () => {\n return guard(\n getStoreConfig(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckoutConfig),\n );\n });\n\n const getContextConfig = createSelector(\n (state: ConfigState) => state.data && state.data.context,\n (data) => () => data,\n );\n\n const getExternalSource = createSelector(\n (state: ConfigState) => state.meta && state.meta.externalSource,\n (data) => () => data,\n );\n\n const getHost = createSelector(\n (state: ConfigState) => state.meta?.host,\n (data) => () => data,\n );\n\n const getLocale = createSelector(\n (state: ConfigState) => state.meta?.locale,\n (data) => () => data,\n );\n\n const getVariantIdentificationToken = createSelector(\n (state: ConfigState) => state.meta && state.meta.variantIdentificationToken,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ConfigState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ConfigState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (state: ConfigState = DEFAULT_STATE, formState: FormFieldsState): ConfigSelector => {\n return {\n getConfig: getConfig(state),\n getFlashMessages: getFlashMessages(state),\n getStoreConfig: getStoreConfig(state, { formState }),\n getStoreConfigOrThrow: getStoreConfigOrThrow(state, { formState }),\n getContextConfig: getContextConfig(state),\n getExternalSource: getExternalSource(state),\n getHost: getHost(state),\n getLocale: getLocale(state),\n getVariantIdentificationToken: getVariantIdentificationToken(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport Country from './country';\nimport CountryState, { DEFAULT_STATE } from './country-state';\n\nexport default interface CountrySelector {\n getCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CountrySelectorFactory = (state: CountryState) => CountrySelector;\n\nexport function createCountrySelectorFactory(): CountrySelectorFactory {\n const getCountries = createSelector(\n (state: CountryState) => state.data,\n (countries) => () => countries,\n );\n\n const getLoadError = createSelector(\n (state: CountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CountryState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CountryState = DEFAULT_STATE): CountrySelector => {\n return {\n getCountries: getCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport CustomerStrategyState, { DEFAULT_STATE } from './customer-strategy-state';\n\nexport default interface CustomerStrategySelector {\n getSignInError(methodId?: string): Error | undefined;\n getSignOutError(methodId?: string): Error | undefined;\n getExecutePaymentMethodCheckoutError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isSigningIn(methodId?: string): boolean;\n isSigningOut(methodId?: string): boolean;\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type CustomerStrategySelectorFactory = (\n state: CustomerStrategyState,\n) => CustomerStrategySelector;\n\nexport function createCustomerStrategySelectorFactory(): CustomerStrategySelectorFactory {\n const getSignInError = createSelector(\n (state: CustomerStrategyState) => state.errors.signInMethodId,\n (state: CustomerStrategyState) => state.errors.signInError,\n (signInMethodId, signInError) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return;\n }\n\n return signInError;\n },\n );\n\n const getSignOutError = createSelector(\n (state: CustomerStrategyState) => state.errors.signOutMethodId,\n (state: CustomerStrategyState) => state.errors.signOutError,\n (signOutMethodId, signOutError) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return;\n }\n\n return signOutError;\n },\n );\n\n const getExecutePaymentMethodCheckoutError = createSelector(\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutError,\n (executePaymentMethodCheckoutMethodId, executePaymentMethodCheckoutError) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return;\n }\n\n return executePaymentMethodCheckoutError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: CustomerStrategyState) => state.errors.initializeMethodId,\n (state: CustomerStrategyState) => state.errors.initializeErrors,\n (initializeMethodId, initializeErrors) => (methodId?: string) => {\n if (!initializeMethodId || !initializeErrors) {\n return;\n }\n\n if (methodId) {\n return initializeErrors[methodId];\n }\n\n return initializeErrors[initializeMethodId];\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: CustomerStrategyState) => state.errors.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isSigningIn = createSelector(\n (state: CustomerStrategyState) => state.statuses.signInMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningIn,\n (signInMethodId, isSigningIn) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningIn;\n },\n );\n\n const isSigningOut = createSelector(\n (state: CustomerStrategyState) => state.statuses.signOutMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningOut,\n (signOutMethodId, isSigningOut) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningOut;\n },\n );\n\n const isExecutingPaymentMethodCheckout = createSelector(\n (state: CustomerStrategyState) => state.statuses.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.statuses.isExecutingPaymentMethodCheckout,\n (executePaymentMethodCheckoutMethodId, isExecutingPaymentMethodCheckout) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return false;\n }\n\n return !!isExecutingPaymentMethodCheckout;\n },\n );\n\n const isInitializing = createSelector(\n (state: CustomerStrategyState) => state.statuses.initializeMethodId,\n (state: CustomerStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: CustomerStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: CustomerStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: CustomerStrategyState = DEFAULT_STATE): CustomerStrategySelector => {\n return {\n getSignInError: getSignInError(state),\n getSignOutError: getSignOutError(state),\n getExecutePaymentMethodCheckoutError: getExecutePaymentMethodCheckoutError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isSigningIn: isSigningIn(state),\n isSigningOut: isSigningOut(state),\n isExecutingPaymentMethodCheckout: isExecutingPaymentMethodCheckout(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport GiftCertificate from './gift-certificate';\nimport GiftCertificateState, { DEFAULT_STATE } from './gift-certificate-state';\n\nexport default interface GiftCertificateSelector {\n getGiftCertificates(): GiftCertificate[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type GiftCertificateSelectorFactory = (\n state: GiftCertificateState,\n) => GiftCertificateSelector;\n\nexport function createGiftCertificateSelectorFactory(): GiftCertificateSelectorFactory {\n const getGiftCertificates = createSelector(\n (state: GiftCertificateState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: GiftCertificateState) => state.errors.removeGiftCertificateError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: GiftCertificateState) => state.errors.applyGiftCertificateError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isApplyingGiftCertificate,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isRemovingGiftCertificate,\n (status) => () => status,\n );\n\n return memoizeOne((state: GiftCertificateState = DEFAULT_STATE): GiftCertificateSelector => {\n return {\n getGiftCertificates: getGiftCertificates(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { filter, flatMap, isMatch, values } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\nimport { createSelector } from '../../common/selector';\nimport { guard } from '../../common/utility';\nimport PaymentMethod from '../payment-method';\n\nimport PaymentInstrument, { CardInstrument } from './instrument';\nimport InstrumentState, { DEFAULT_STATE, InstrumentMeta } from './instrument-state';\nimport supportedInstruments from './supported-payment-instruments';\n\nexport default interface InstrumentSelector {\n getCardInstrument(instrumentId: string): CardInstrument | undefined;\n getCardInstrumentOrThrow(instrumentId: string): CardInstrument;\n getInstruments(): PaymentInstrument[] | undefined;\n getInstrumentsByPaymentMethod(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n getInstrumentsMeta(): InstrumentMeta | undefined;\n getLoadError(): Error | undefined;\n getDeleteError(instrumentId?: string): Error | undefined;\n isLoading(): boolean;\n isDeleting(instrumentId?: string): boolean;\n}\n\nexport type InstrumentSelectorFactory = (state: InstrumentState) => InstrumentSelector;\n\nexport function createInstrumentSelectorFactory(): InstrumentSelectorFactory {\n const getInstrumentsByPaymentMethod = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => (paymentMethod: PaymentMethod) => {\n if (!instruments) {\n return;\n }\n\n const paymentMethodKey = paymentMethod.gateway\n ? `${paymentMethod.gateway}.${paymentMethod.id}`\n : paymentMethod.id;\n\n const currentMethod = supportedInstruments[paymentMethodKey];\n\n if (!currentMethod) {\n return [];\n }\n\n return filter(instruments, currentMethod);\n },\n );\n\n const getCardInstrument = createSelector(\n (state: InstrumentState) => state.data,\n (instruments = []) =>\n (instrumentId: string) => {\n const cards = values(supportedInstruments);\n\n return instruments.find(\n (instrument): instrument is CardInstrument =>\n instrument.bigpayToken === instrumentId &&\n instrument.type === 'card' &&\n cards.some((card) => isMatch(instrument, card)),\n );\n },\n );\n\n const getCardInstrumentOrThrow = createSelector(\n getCardInstrument,\n (getCardInstrument) => (instrumentId: string) => {\n return guard(\n getCardInstrument(instrumentId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentInstrument),\n );\n },\n );\n\n const getInstruments = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => () => {\n if (!instruments) {\n return;\n }\n\n const allSupportedInstruments = flatMap(supportedInstruments, (supportedProvider) =>\n filter(\n instruments,\n (instrument: PaymentInstrument): instrument is PaymentInstrument => {\n return isMatch(instrument, supportedProvider);\n },\n ),\n );\n\n return allSupportedInstruments;\n },\n );\n\n const getInstrumentsMeta = createSelector(\n (state: InstrumentState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: InstrumentState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getDeleteError = createSelector(\n (state: InstrumentState) => state.errors.failedInstrument,\n (state: InstrumentState) => state.errors.deleteError,\n (failedInstrument, deleteError) => (instrumentId?: string) => {\n if (instrumentId && failedInstrument !== instrumentId) {\n return;\n }\n\n return deleteError;\n },\n );\n\n const isLoading = createSelector(\n (state: InstrumentState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isDeleting = createSelector(\n (state: InstrumentState) => state.statuses.deletingInstrument,\n (state: InstrumentState) => state.statuses.isDeleting,\n (deletingInstrument, isDeleting) => (instrumentId?: string) => {\n if (instrumentId && deletingInstrument !== instrumentId) {\n return false;\n }\n\n return !!isDeleting;\n },\n );\n\n return memoizeOne((state: InstrumentState = DEFAULT_STATE): InstrumentSelector => {\n return {\n getCardInstrument: getCardInstrument(state),\n getCardInstrumentOrThrow: getCardInstrumentOrThrow(state),\n getInstruments: getInstruments(state),\n getInstrumentsByPaymentMethod: getInstrumentsByPaymentMethod(state),\n getInstrumentsMeta: getInstrumentsMeta(state),\n getLoadError: getLoadError(state),\n getDeleteError: getDeleteError(state),\n isLoading: isLoading(state),\n isDeleting: isDeleting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport FormField from './form-field';\nimport FormFieldsState, { DEFAULT_STATE } from './form-fields-state';\n\nexport default interface FormSelector {\n getShippingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getBillingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getCustomerAccountFields(): FormField[];\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type FormSelectorFactory = (state: FormFieldsState) => FormSelector;\n\nexport function createFormSelectorFactory(): FormSelectorFactory {\n const getShippingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.shippingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getBillingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.billingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getCustomerAccountFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) => () => formFields ? formFields.customerAccount : [],\n );\n\n const getLoadError = createSelector(\n (state: FormFieldsState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: FormFieldsState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n function processField(\n field: FormField,\n countries: Country[],\n selectedCountry?: Country,\n ): FormField {\n if (field.name === 'countryCode') {\n return processCountry(field, countries, selectedCountry);\n }\n\n if (field.name === 'stateOrProvince') {\n return processProvince(field, selectedCountry);\n }\n\n if (field.name === 'postalCode') {\n return processsPostCode(field, selectedCountry);\n }\n\n return field;\n }\n\n function processCountry(\n field: FormField,\n countries: Country[] = [],\n country?: Country,\n ): FormField {\n if (!countries.length) {\n return field;\n }\n\n const { code = '' } = country || {};\n const items = countries.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n options: { items },\n default: code,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processProvince(field: FormField, country?: Country): FormField {\n const { subdivisions = [], requiresState } = country || {};\n\n if (!subdivisions.length) {\n return {\n ...field,\n required: requiresState == null ? false : requiresState,\n };\n }\n\n const items = subdivisions.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n name: 'stateOrProvinceCode',\n options: { items },\n required: requiresState == null ? true : requiresState,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processsPostCode(field: FormField, country?: Country): FormField {\n const { hasPostalCodes = [] } = country || {};\n\n if (hasPostalCodes === undefined) {\n return field;\n }\n\n return { ...field, required: Boolean(hasPostalCodes) };\n }\n\n return memoizeOne((state: FormFieldsState = DEFAULT_STATE): FormSelector => {\n return {\n getShippingAddressFields: getShippingAddressFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE } from './payment-method-state';\n\nexport default interface PaymentMethodSelector {\n getPaymentMethods(): PaymentMethod[] | undefined;\n getPaymentMethodsMeta(): PaymentMethodMeta | undefined;\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n getPaymentMethodOrThrow(methodId: string, gatewayId?: string): PaymentMethod;\n getLoadError(): Error | undefined;\n getLoadMethodError(methodId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingMethod(methodId?: string): boolean;\n}\n\nexport type PaymentMethodSelectorFactory = (state: PaymentMethodState) => PaymentMethodSelector;\n\nexport function createPaymentMethodSelectorFactory(): PaymentMethodSelectorFactory {\n const getPaymentMethods = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => () => paymentMethods,\n );\n\n const getPaymentMethodsMeta = createSelector(\n (state: PaymentMethodState) => state.meta,\n (meta) => () => meta,\n );\n\n const getPaymentMethod = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => (methodId: string, gatewayId?: string) => {\n return gatewayId\n ? find(paymentMethods, { id: methodId, gateway: gatewayId })\n : find(paymentMethods, { id: methodId });\n },\n );\n\n const getPaymentMethodOrThrow = createSelector(\n getPaymentMethod,\n (getPaymentMethod) => (methodId: string, gatewayId?: string) => {\n return guard(\n getPaymentMethod(methodId, gatewayId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentMethod),\n );\n },\n );\n\n const getLoadError = createSelector(\n (state: PaymentMethodState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getLoadMethodError = createSelector(\n (state: PaymentMethodState) => state.errors.loadMethodId,\n (state: PaymentMethodState) => state.errors.loadMethodError,\n (loadMethodId, loadMethodError) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return;\n }\n\n return loadMethodError;\n },\n );\n\n const isLoading = createSelector(\n (state: PaymentMethodState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isLoadingMethod = createSelector(\n (state: PaymentMethodState) => state.statuses.loadMethodId,\n (state: PaymentMethodState) => state.statuses.isLoadingMethod,\n (loadMethodId, isLoadingMethod) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return false;\n }\n\n return !!isLoadingMethod;\n },\n );\n\n return memoizeOne((state: PaymentMethodState = DEFAULT_STATE): PaymentMethodSelector => {\n return {\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethodsMeta: getPaymentMethodsMeta(state),\n getPaymentMethod: getPaymentMethod(state),\n getPaymentMethodOrThrow: getPaymentMethodOrThrow(state),\n getLoadError: getLoadError(state),\n getLoadMethodError: getLoadMethodError(state),\n isLoading: isLoading(state),\n isLoadingMethod: isLoadingMethod(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport PaymentStrategyState, { DEFAULT_STATE } from './payment-strategy-state';\n\ninterface InitiaizedQuery {\n methodId: string;\n gatewayId?: string;\n}\n\nexport default interface PaymentStrategySelector {\n getInitializeError(methodId?: string): Error | undefined;\n getExecuteError(methodId?: string): Error | undefined;\n getFinalizeError(methodId?: string): Error | undefined;\n getWidgetInteractingError(methodId?: string): Error | undefined;\n isInitializing(methodId?: string): boolean;\n isInitialized(query: InitiaizedQuery): boolean;\n isExecuting(methodId?: string): boolean;\n isFinalizing(methodId?: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type PaymentStrategySelectorFactory = (\n state: PaymentStrategyState,\n) => PaymentStrategySelector;\n\nexport function createPaymentStrategySelectorFactory(): PaymentStrategySelectorFactory {\n const getInitializeError = createSelector(\n (state: PaymentStrategyState) => state.errors.initializeMethodId,\n (state: PaymentStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getExecuteError = createSelector(\n (state: PaymentStrategyState) => state.errors.executeMethodId,\n (state: PaymentStrategyState) => state.errors.executeError,\n (executeMethodId, executeError) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return;\n }\n\n return executeError;\n },\n );\n\n const getFinalizeError = createSelector(\n (state: PaymentStrategyState) => state.errors.finalizeMethodId,\n (state: PaymentStrategyState) => state.errors.finalizeError,\n (finalizeMethodId, finalizeError) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return;\n }\n\n return finalizeError;\n },\n );\n\n const getWidgetInteractingError = createSelector(\n (state: PaymentStrategyState) => state.errors.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isInitializing = createSelector(\n (state: PaymentStrategyState) => state.statuses.initializeMethodId,\n (state: PaymentStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (key?: string) => {\n if (key && initializeMethodId !== key) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: PaymentStrategyState) => state.data,\n (data) => (query: InitiaizedQuery) => {\n const key = query.gatewayId ? `${query.methodId}.${query.gatewayId}` : query.methodId;\n\n return !!(data[key] && data[key].isInitialized);\n },\n );\n\n const isExecuting = createSelector(\n (state: PaymentStrategyState) => state.statuses.executeMethodId,\n (state: PaymentStrategyState) => state.statuses.isExecuting,\n (executeMethodId, isExecuting) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return false;\n }\n\n return !!isExecuting;\n },\n );\n\n const isFinalizing = createSelector(\n (state: PaymentStrategyState) => state.statuses.finalizeMethodId,\n (state: PaymentStrategyState) => state.statuses.isFinalizing,\n (finalizeMethodId, isFinalizing) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return false;\n }\n\n return !!isFinalizing;\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: PaymentStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: PaymentStrategyState = DEFAULT_STATE): PaymentStrategySelector => {\n return {\n getInitializeError: getInitializeError(state),\n getExecuteError: getExecuteError(state),\n getFinalizeError: getFinalizeError(state),\n getWidgetInteractingError: getWidgetInteractingError(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isExecuting: isExecuting(state),\n isFinalizing: isFinalizing(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { objectFlatten, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionResult, SearchArea } from './pickup-option';\nimport PickupOptionState, { DEFAULT_STATE } from './pickup-option-state';\n\nexport default interface PickupOptionSelector {\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type PickupOptionSelectorFactory = (state: PickupOptionState) => PickupOptionSelector;\n\nexport function createPickupOptionSelectorFactory(): PickupOptionSelectorFactory {\n const getPickupOptions = createSelector(\n (state: PickupOptionState) => state.data,\n (pickupOptions) => (consignmentId: string, searchArea: SearchArea) => {\n if (!pickupOptions) {\n return;\n }\n\n const flattenedParams = objectFlatten({ consignmentId, searchArea });\n const sortedFlattenedParams = objectWithSortedKeys(flattenedParams);\n const keyString = btoa(`${JSON.stringify(sortedFlattenedParams)}`);\n\n return pickupOptions[keyString];\n },\n );\n\n const getLoadError = createSelector(\n (state: PickupOptionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: PickupOptionState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: PickupOptionState = DEFAULT_STATE): PickupOptionSelector => {\n return {\n getPickupOptions: getPickupOptions(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport ShippingCountryState, { DEFAULT_STATE } from './shipping-country-state';\n\nexport default interface ShippingCountrySelector {\n getShippingCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ShippingCountrySelectorFactory = (\n state: ShippingCountryState,\n) => ShippingCountrySelector;\n\nexport function createShippingCountrySelectorFactory(): ShippingCountrySelectorFactory {\n const getShippingCountries = createSelector(\n (state: ShippingCountryState) => state.data,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ShippingCountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ShippingCountryState) => state.statuses.isLoading,\n (status) => () => !!status,\n );\n\n return memoizeOne((state: ShippingCountryState = DEFAULT_STATE): ShippingCountrySelector => {\n return {\n getShippingCountries: getShippingCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport ShippingStrategyState, { DEFAULT_STATE } from './shipping-strategy-state';\n\nexport default interface ShippingStrategySelector {\n getUpdateAddressError(methodId?: string): Error | undefined;\n getSelectOptionError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isUpdatingAddress(methodId?: string): boolean;\n isSelectingOption(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type ShippingStrategySelectorFactory = (\n state: ShippingStrategyState,\n) => ShippingStrategySelector;\n\nexport function createShippingStrategySelectorFactory(): ShippingStrategySelectorFactory {\n const getUpdateAddressError = createSelector(\n (state: ShippingStrategyState) => state.errors.updateAddressMethodId,\n (state: ShippingStrategyState) => state.errors.updateAddressError,\n (updateAddressMethodId, updateAddressError) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return;\n }\n\n return updateAddressError;\n },\n );\n\n const getSelectOptionError = createSelector(\n (state: ShippingStrategyState) => state.errors.selectOptionMethodId,\n (state: ShippingStrategyState) => state.errors.selectOptionError,\n (selectOptionMethodId, selectOptionError) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return;\n }\n\n return selectOptionError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: ShippingStrategyState) => state.errors.initializeMethodId,\n (state: ShippingStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: ShippingStrategyState) => state.errors.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isUpdatingAddress = createSelector(\n (state: ShippingStrategyState) => state.statuses.updateAddressMethodId,\n (state: ShippingStrategyState) => state.statuses.isUpdatingAddress,\n (updateAddressMethodId, isUpdatingAddress) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return false;\n }\n\n return !!isUpdatingAddress;\n },\n );\n\n const isSelectingOption = createSelector(\n (state: ShippingStrategyState) => state.statuses.selectOptionMethodId,\n (state: ShippingStrategyState) => state.statuses.isSelectingOption,\n (selectOptionMethodId, isSelectingOption) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return false;\n }\n\n return !!isSelectingOption;\n },\n );\n\n const isInitializing = createSelector(\n (state: ShippingStrategyState) => state.statuses.initializeMethodId,\n (state: ShippingStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: ShippingStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: ShippingStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: ShippingStrategyState = DEFAULT_STATE): ShippingStrategySelector => {\n return {\n getUpdateAddressError: getUpdateAddressError(state),\n getSelectOptionError: getSelectOptionError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isUpdatingAddress: isUpdatingAddress(state),\n isSelectingOption: isSelectingOption(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { AddressRequestBody, isAddressEqual } from '../address';\nimport { CartSelector, PhysicalItem } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Consignment from './consignment';\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\nimport ShippingOption from './shipping-option';\n\nexport default interface ConsignmentSelector {\n getConsignments(): Consignment[] | undefined;\n getConsignmentsOrThrow(): Consignment[];\n getConsignmentById(id: string): Consignment | undefined;\n getConsignmentByAddress(address: AddressRequestBody): Consignment | undefined;\n getShippingOption(): ShippingOption | undefined;\n getLoadError(): Error | undefined;\n getCreateError(): Error | undefined;\n getLoadShippingOptionsError(): Error | undefined;\n getUnassignedItems(): PhysicalItem[];\n getUpdateError(consignmentId?: string): Error | undefined;\n getDeleteError(consignmentId?: string): Error | undefined;\n getItemAssignmentError(address: AddressRequestBody): Error | undefined;\n getUpdateShippingOptionError(consignmentId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingShippingOptions(): boolean;\n isCreating(): boolean;\n isUpdating(consignmentId?: string): boolean;\n isDeleting(consignmentId?: string): boolean;\n isAssigningItems(address: AddressRequestBody): boolean;\n isUpdatingShippingOption(consignmentId?: string): boolean;\n}\n\nexport type ConsignmentSelectorFactory = (\n state: ConsignmentState,\n cart: CartSelector,\n) => ConsignmentSelector;\n\ninterface ConsignmentSelectorDependencies {\n cart: CartSelector;\n}\n\nexport function createConsignmentSelectorFactory(): ConsignmentSelectorFactory {\n const getConsignments = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => consignments,\n );\n\n const getConsignmentsOrThrow = createSelector(getConsignments, (getConsignments) => () => {\n return guard(\n getConsignments(),\n () => new MissingDataError(MissingDataErrorType.MissingConsignments),\n );\n });\n\n const getConsignmentById = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (id: string) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, { id });\n },\n );\n\n const getConsignmentByAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (address: AddressRequestBody) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, (consignment) =>\n isAddressEqual(consignment.shippingAddress, address),\n );\n },\n );\n\n const getShippingOption = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n if (consignments && consignments.length) {\n return consignments[0].selectedShippingOption;\n }\n },\n );\n\n const getLoadError = createSelector(\n (state: ConsignmentState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getCreateError = createSelector(\n (state: ConsignmentState) => state.errors.createError,\n (error) => () => error,\n );\n\n const getLoadShippingOptionsError = createSelector(\n (state: ConsignmentState) => state.errors.loadShippingOptionsError,\n (error) => () => error,\n );\n\n const getUnassignedItems = createSelector(\n getConsignments,\n (_: ConsignmentState, { cart }: ConsignmentSelectorDependencies) => cart.getCart,\n (getConsignments, getCart) => () => {\n const cart = getCart();\n\n if (!cart) {\n return [];\n }\n\n const assignedLineItemIds = (getConsignments() || []).reduce(\n (itemIds, consignment) => itemIds.concat(consignment.lineItemIds),\n [] as string[],\n );\n\n return (cart.lineItems.physicalItems || []).filter(\n (item) => assignedLineItemIds.indexOf(item.id as string) < 0,\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: ConsignmentState) => state.errors.updateError,\n (updateError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateError[consignmentId];\n }\n\n return find(updateError);\n },\n );\n\n const getDeleteError = createSelector(\n (state: ConsignmentState) => state.errors.deleteError,\n (deleteError) => (consignmentId?: string) => {\n if (consignmentId) {\n return deleteError[consignmentId];\n }\n\n return find(deleteError);\n },\n );\n\n const getItemAssignmentError = createSelector(\n getConsignmentByAddress,\n getUpdateError,\n getCreateError,\n (getConsignmentByAddress, getUpdateError, getCreateError) =>\n (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? getUpdateError(consignment.id) : getCreateError();\n },\n );\n\n const getUpdateShippingOptionError = createSelector(\n (state: ConsignmentState) => state.errors.updateShippingOptionError,\n (updateShippingOptionError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateShippingOptionError[consignmentId];\n }\n\n return find(updateShippingOptionError);\n },\n );\n\n const isLoading = createSelector(\n (state: ConsignmentState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isLoadingShippingOptions = createSelector(\n (state: ConsignmentState) => state.statuses.isLoadingShippingOptions,\n (isLoadingShippingOptions) => () => isLoadingShippingOptions === true,\n );\n\n const isCreating = createSelector(\n (state: ConsignmentState) => state.statuses.isCreating,\n (isCreating) => () => isCreating === true,\n );\n\n const isUpdating = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdating,\n (isUpdating) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdating[consignmentId] === true;\n }\n\n return find(isUpdating) === true;\n },\n );\n\n const isDeleting = createSelector(\n (state: ConsignmentState) => state.statuses.isDeleting,\n (isDeleting) => (consignmentId?: string) => {\n if (consignmentId) {\n return isDeleting[consignmentId] === true;\n }\n\n return find(isDeleting) === true;\n },\n );\n\n const isAssigningItems = createSelector(\n getConsignmentByAddress,\n isUpdating,\n isCreating,\n (getConsignmentByAddress, isUpdating, isCreating) => (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? isUpdating(consignment.id) : isCreating();\n },\n );\n\n const isUpdatingShippingOption = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdatingShippingOption,\n (isUpdatingShippingOption) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdatingShippingOption[consignmentId] === true;\n }\n\n return find(isUpdatingShippingOption) === true;\n },\n );\n\n return memoizeOne(\n (state: ConsignmentState = DEFAULT_STATE, cart: CartSelector): ConsignmentSelector => {\n return {\n getConsignments: getConsignments(state),\n getConsignmentsOrThrow: getConsignmentsOrThrow(state),\n getConsignmentById: getConsignmentById(state),\n getConsignmentByAddress: getConsignmentByAddress(state),\n getShippingOption: getShippingOption(state),\n getLoadError: getLoadError(state),\n getCreateError: getCreateError(state),\n getLoadShippingOptionsError: getLoadShippingOptionsError(state),\n getUnassignedItems: getUnassignedItems(state, { cart }),\n getUpdateError: getUpdateError(state),\n getDeleteError: getDeleteError(state),\n getItemAssignmentError: getItemAssignmentError(state),\n getUpdateShippingOptionError: getUpdateShippingOptionError(state),\n isLoading: isLoading(state),\n isLoadingShippingOptions: isLoadingShippingOptions(state),\n isCreating: isCreating(state),\n isUpdating: isUpdating(state),\n isDeleting: isDeleting(state),\n isAssigningItems: isAssigningItems(state),\n isUpdatingShippingOption: isUpdatingShippingOption(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { CartSelector } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector, GiftCertificateSelector } from '../coupon';\nimport { CustomerSelector } from '../customer';\nimport { ConsignmentSelector } from '../shipping';\n\nimport Checkout from './checkout';\nimport CheckoutState, { DEFAULT_STATE } from './checkout-state';\n\nexport default interface CheckoutSelector {\n getCheckout(): Checkout | undefined;\n getCheckoutOrThrow(): Checkout;\n getOutstandingBalance(useStoreCredit?: boolean): number | undefined;\n getLoadError(): Error | undefined;\n getUpdateError(): Error | undefined;\n isExecutingSpamCheck(): boolean;\n isLoading(): boolean;\n isUpdating(): boolean;\n}\n\nexport type CheckoutSelectorFactory = (\n state: CheckoutState,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n) => CheckoutSelector;\n\ninterface CheckoutSelectorDependencies {\n billingAddress: BillingAddressSelector;\n cart: CartSelector;\n consignments: ConsignmentSelector;\n coupons: CouponSelector;\n customer: CustomerSelector;\n giftCertificates: GiftCertificateSelector;\n}\n\nexport function createCheckoutSelectorFactory(): CheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: CheckoutState) => state.data,\n (_: CheckoutState, { billingAddress }: CheckoutSelectorDependencies) =>\n billingAddress.getBillingAddress,\n (_: CheckoutState, { cart }: CheckoutSelectorDependencies) => cart.getCart,\n (_: CheckoutState, { customer }: CheckoutSelectorDependencies) => customer.getCustomer,\n (_: CheckoutState, { consignments }: CheckoutSelectorDependencies) =>\n consignments.getConsignments,\n (_: CheckoutState, { coupons }: CheckoutSelectorDependencies) => coupons.getCoupons,\n (_: CheckoutState, { giftCertificates }: CheckoutSelectorDependencies) =>\n giftCertificates.getGiftCertificates,\n (\n data,\n getBillingAddress,\n getCart,\n getCustomer,\n getConsignments,\n getCoupons,\n getGiftCertificates,\n ) =>\n () => {\n const billingAddress = getBillingAddress();\n const cart = getCart();\n const customer = getCustomer();\n const consignments = getConsignments() || [];\n const coupons = getCoupons() || [];\n const giftCertificates = getGiftCertificates() || [];\n\n if (!data || !cart || !customer) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n cart,\n customer,\n consignments,\n coupons,\n giftCertificates,\n };\n },\n );\n\n const getCheckoutOrThrow = createSelector(getCheckout, (getCheckout) => () => {\n return guard(\n getCheckout(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckout),\n );\n });\n\n const getOutstandingBalance = createSelector(\n getCheckout,\n (getCheckout) => (useStoreCredit?: boolean) => {\n const checkout = getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const grandTotal = checkout.grandTotal || 0;\n const storeCredit = checkout.customer.storeCredit || 0;\n\n return useStoreCredit\n ? Math.max(grandTotal - storeCredit, 0)\n : checkout.outstandingBalance;\n },\n );\n\n const getLoadError = createSelector(\n (state: CheckoutState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getUpdateError = createSelector(\n (state: CheckoutState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isExecutingSpamCheck = createSelector(\n (state: CheckoutState) => state.statuses.isExecutingSpamCheck,\n (isExecutingSpamCheck) => () => isExecutingSpamCheck === true,\n );\n\n const isLoading = createSelector(\n (state: CheckoutState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isUpdating = createSelector(\n (state: CheckoutState) => state.statuses.isUpdating,\n (isUpdating) => () => isUpdating === true,\n );\n\n return memoizeOne(\n (\n state: CheckoutState = DEFAULT_STATE,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n ): CheckoutSelector => {\n return {\n getCheckout: getCheckout(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getCheckoutOrThrow: getCheckoutOrThrow(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getOutstandingBalance: getOutstandingBalance(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getLoadError: getLoadError(state),\n getUpdateError: getUpdateError(state),\n isExecutingSpamCheck: isExecutingSpamCheck(state),\n isLoading: isLoading(state),\n isUpdating: isUpdating(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector } from '../coupon';\nimport OrderBillingAddressSelector from '../order-billing-address/order-billing-address-selector';\n\nimport Order from './order';\nimport OrderState, { DEFAULT_STATE, OrderMetaState } from './order-state';\n\nexport default interface OrderSelector {\n getOrder(): Order | undefined;\n getOrderOrThrow(): Order;\n getOrderMeta(): OrderMetaState | undefined;\n getLoadError(): Error | undefined;\n getPaymentId(methodId: string): string | undefined;\n isLoading(): boolean;\n}\n\nexport type OrderSelectorFactory = (\n state: OrderState,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n) => OrderSelector;\n\ninterface OrderSelectorDependencies {\n billingAddress: OrderBillingAddressSelector;\n coupons: CouponSelector;\n}\n\nexport function createOrderSelectorFactory(): OrderSelectorFactory {\n const getOrder = createSelector(\n (state: OrderState) => state.data,\n (_: OrderState, { billingAddress }: OrderSelectorDependencies) =>\n billingAddress.getOrderBillingAddress(),\n (_: OrderState, { coupons }: OrderSelectorDependencies) => coupons.getCoupons(),\n (data, billingAddress, coupons = []) =>\n () => {\n if (!data || !billingAddress) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n coupons,\n };\n },\n );\n\n const getOrderOrThrow = createSelector(getOrder, (getOrder) => () => {\n return guard(getOrder(), () => new MissingDataError(MissingDataErrorType.MissingOrder));\n });\n\n const getOrderMeta = createSelector(\n (state: OrderState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: OrderState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getPaymentId = createSelector(\n (state: OrderState) => state.data?.payments,\n (payments = []) =>\n (methodId: string) => {\n const currentPayment = payments.find(({ providerId }) => providerId === methodId);\n\n return currentPayment?.paymentId;\n },\n );\n\n const isLoading = createSelector(\n (state: OrderState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (\n state: OrderState = DEFAULT_STATE,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n ): OrderSelector => {\n return {\n getOrder: getOrder(state, { billingAddress, coupons }),\n getOrderOrThrow: getOrderOrThrow(state, { billingAddress, coupons }),\n getOrderMeta: getOrderMeta(state),\n getLoadError: getLoadError(state),\n getPaymentId: getPaymentId(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport StoreCreditState, { DEFAULT_STATE } from './store-credit-state';\n\nexport default interface StoreCreditSelector {\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n}\n\nexport type StoreCreditSelectorFactory = (state: StoreCreditState) => StoreCreditSelector;\n\nexport function createStoreCreditSelectorFactory(): StoreCreditSelectorFactory {\n const getApplyError = createSelector(\n (state: StoreCreditState) => state.errors.applyError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: StoreCreditState) => !!state.statuses.isApplying,\n (status) => () => status,\n );\n\n return memoizeOne((state: StoreCreditState = DEFAULT_STATE): StoreCreditSelector => {\n return {\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport SubscriptionsState, { DEFAULT_STATE } from './subscriptions-state';\n\nexport default interface SubscriptionsSelector {\n getUpdateError(): Error | undefined;\n isUpdating(): boolean;\n}\n\nexport type SubscriptionsSelectorFactory = (state: SubscriptionsState) => SubscriptionsSelector;\n\nexport function createSubscriptionsSelectorFactory(): SubscriptionsSelectorFactory {\n const getUpdateError = createSelector(\n (state: SubscriptionsState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: SubscriptionsState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n return memoizeOne((state: SubscriptionsState = DEFAULT_STATE): SubscriptionsSelector => {\n return {\n getUpdateError: getUpdateError(state),\n isUpdating: isUpdating(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { Extension, ExtensionRegion } from './extension';\nimport { DEFAULT_STATE, ExtensionState } from './extension-state';\n\nexport interface ExtensionSelector {\n getExtensions(): Extension[] | undefined;\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ExtensionSelectorFactory = (state: ExtensionState) => ExtensionSelector;\n\nexport function createExtensionSelectorFactory(): ExtensionSelectorFactory {\n const getExtensions = createSelector(\n (state: ExtensionState) => state.data,\n (data) => () => data,\n );\n\n const getExtensionByRegion = createSelector(\n (state: ExtensionState) => state.data,\n (data) => (region: ExtensionRegion) => data?.find((e) => e.region === region),\n );\n\n const getLoadError = createSelector(\n (state: ExtensionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ExtensionState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n return memoizeOne((state: ExtensionState = DEFAULT_STATE): ExtensionSelector => {\n return {\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { createDataStore } from '@bigcommerce/data-store';\n\nimport { createRequestErrorFactory } from '../common/error';\n\nimport CheckoutStore, { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport createActionTransformer from './create-action-transformer';\nimport createCheckoutStoreReducer from './create-checkout-store-reducer';\nimport { createInternalCheckoutSelectorsFactory } from './create-internal-checkout-selectors';\n\nexport default function createCheckoutStore(\n initialState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n\n return createDataStore(createCheckoutStoreReducer(), initialState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnrecoverableError } from './errors';\nimport RequestErrorFactory from './request-error-factory';\n\nexport default function createRequestErrorFactory(): RequestErrorFactory {\n const factory = new RequestErrorFactory();\n\n const unrecoverableErrorTypes = [\n 'catalog_only',\n 'empty_cart',\n 'invalid_order_id',\n 'invalid_order_token',\n 'missing_order_token',\n 'missing_provider_token',\n 'missing_shipping_method',\n 'order_completion_error',\n 'order_could_not_be_finalized_error',\n 'order_create_failed',\n 'provider_fatal_error',\n 'provider_setup_error',\n 'stock_too_low',\n ];\n\n unrecoverableErrorTypes.forEach((type) => {\n factory.register(type, (response, message) => new UnrecoverableError(response, message));\n });\n\n factory.register(\n 'invalid_payment_provider',\n (response) => new PaymentMethodInvalidError(response),\n );\n factory.register(\n 'payment_config_not_found',\n (response) => new PaymentMethodInvalidError(response),\n );\n\n return factory;\n}\n","import { Action } from '@bigcommerce/data-store';\nimport { from, Observable, Subscribable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { RequestErrorFactory } from '../common/error';\n\nexport default function createActionTransformer(\n requestErrorFactory: RequestErrorFactory,\n): (action: Subscribable) => Observable {\n return (action$) =>\n from(action$).pipe(\n catchError((action) => {\n if (action instanceof Error || action.payload instanceof Error) {\n throw action;\n }\n\n if (isResponse(action.payload)) {\n const message = action.payload.body && action.payload.body.detail;\n\n throw {\n ...action,\n payload: requestErrorFactory.createError(action.payload, message),\n };\n }\n\n throw action;\n }),\n );\n}\n\nfunction isResponse(object: any) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n\n return ['body', 'headers', 'status', 'statusText'].every((key) =>\n Object.prototype.hasOwnProperty.call(object, key),\n );\n}\n","import { Action, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { billingAddressReducer } from '../billing';\nimport { cartReducer } from '../cart';\nimport { checkoutButtonReducer } from '../checkout-buttons';\nimport { configReducer } from '../config';\nimport { couponReducer, giftCertificateReducer } from '../coupon';\nimport { customerReducer, customerStrategyReducer } from '../customer';\nimport { extensionReducer } from '../extension';\nimport { formFieldsReducer } from '../form';\nimport { countryReducer } from '../geography';\nimport { orderReducer } from '../order';\nimport { orderBillingAddressReducer } from '../order-billing-address';\nimport { paymentMethodReducer, paymentReducer, paymentStrategyReducer } from '../payment';\nimport { paymentProviderCustomerReducer } from '../payment-provider-customer';\nimport { instrumentReducer } from '../payment/instrument';\nimport { remoteCheckoutReducer } from '../remote-checkout';\nimport {\n consignmentReducer,\n pickupOptionReducer,\n shippingCountryReducer,\n shippingStrategyReducer,\n} from '../shipping';\nimport { signInEmailReducer } from '../signin-email';\nimport { storeCreditReducer } from '../store-credit';\nimport { subscriptionsReducer } from '../subscription';\n\nimport checkoutReducer from './checkout-reducer';\nimport CheckoutStoreState from './checkout-store-state';\n\nexport default function createCheckoutStoreReducer(): Reducer {\n return combineReducers({\n billingAddress: billingAddressReducer,\n cart: cartReducer,\n checkout: checkoutReducer,\n checkoutButton: checkoutButtonReducer,\n config: configReducer,\n consignments: consignmentReducer,\n countries: countryReducer,\n coupons: couponReducer,\n customer: customerReducer,\n customerStrategies: customerStrategyReducer,\n extensions: extensionReducer,\n formFields: formFieldsReducer,\n giftCertificates: giftCertificateReducer,\n instruments: instrumentReducer,\n orderBillingAddress: orderBillingAddressReducer,\n order: orderReducer,\n payment: paymentReducer,\n paymentMethods: paymentMethodReducer,\n paymentStrategies: paymentStrategyReducer,\n pickupOptions: pickupOptionReducer,\n paymentProviderCustomer: paymentProviderCustomerReducer,\n remoteCheckout: remoteCheckoutReducer,\n shippingCountries: shippingCountryReducer,\n shippingStrategies: shippingStrategyReducer,\n signInEmail: signInEmailReducer,\n subscriptions: subscriptionsReducer,\n storeCredit: storeCreditReducer,\n });\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator } from '../common/error';\nimport { getDefaultLogger } from '../common/log';\nimport { getEnvironment } from '../common/utility';\nimport { ConfigActionCreator, ConfigRequestSender, ConfigState, ConfigWindow } from '../config';\nimport {\n CouponActionCreator,\n CouponRequestSender,\n GiftCertificateActionCreator,\n GiftCertificateRequestSender,\n} from '../coupon';\nimport {\n createCustomerStrategyRegistry,\n createCustomerStrategyRegistryV2,\n CustomerActionCreator,\n CustomerRequestSender,\n CustomerStrategyActionCreator,\n} from '../customer';\nimport {\n createExtensionEventBroadcaster,\n ExtensionActionCreator,\n ExtensionMessenger,\n ExtensionRequestSender,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\nimport { CountryActionCreator, CountryRequestSender } from '../geography';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n createPaymentStrategyRegistry,\n createPaymentStrategyRegistryV2,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { InstrumentActionCreator, InstrumentRequestSender } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n createShippingStrategyRegistry,\n PickupOptionActionCreator,\n PickupOptionRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestSender } from '../signin-email';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport CheckoutService from './checkout-service';\nimport CheckoutValidator from './checkout-validator';\nimport { createCheckoutSelectorsFactory } from './create-checkout-selectors';\nimport createCheckoutStore from './create-checkout-store';\n\n/**\n * Creates an instance of `CheckoutService`.\n *\n * @remarks\n * ```js\n * const service = createCheckoutService();\n *\n * service.subscribe(state => {\n * console.log(state);\n * });\n *\n * service.loadCheckout();\n * ```\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutService`.\n */\nexport default function createCheckoutService(options?: CheckoutServiceOptions): CheckoutService {\n if (document.location.protocol !== 'https:') {\n getDefaultLogger().warn(\n 'The BigCommerce Checkout SDK should not be used on a non-HTTPS page',\n );\n }\n\n if (getEnvironment() !== 'production') {\n getDefaultLogger().warn(\n 'Note that the development build is not optimized. To create a production build, set process\\u200b.env.NODE_ENV to `production`.',\n );\n }\n\n const config: ConfigState = {\n meta: {\n externalSource: options && options.externalSource,\n host: options?.host,\n locale: options?.locale,\n variantIdentificationToken: (window as ConfigWindow).checkoutVariantIdentificationToken,\n },\n errors: {},\n statuses: {},\n };\n const { locale = '', shouldWarnMutation = true } = options || {};\n const requestSender = createRequestSender({ host: options && options.host });\n const store = createCheckoutStore({ config }, { shouldWarnMutation });\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(requestSender);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n const orderActionCreator = new OrderActionCreator(\n orderRequestSender,\n new CheckoutValidator(checkoutRequestSender),\n );\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n defaultPaymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(requestSender),\n );\n const extensionMessenger = new ExtensionMessenger(store);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(requestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(requestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, requestSender, locale),\n customerRegistryV2,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(requestSender)),\n new InstrumentActionCreator(new InstrumentRequestSender(paymentClient, requestSender)),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(\n store,\n paymentClient,\n requestSender,\n spamProtection,\n locale,\n ),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(requestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(createShippingStrategyRegistry(store, requestSender)),\n new SignInEmailActionCreator(new SignInEmailRequestSender(requestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { omit, values } from 'lodash';\n\nimport { Address } from '../address';\nimport { BillingAddress } from '../billing';\nimport { Cart } from '../cart';\nimport { createSelector } from '../common/selector';\nimport { cloneResult as clone } from '../common/utility';\nimport { FlashMessage, FlashMessageType, StoreConfig, UserExperienceSettings } from '../config';\nimport { Coupon, GiftCertificate } from '../coupon';\nimport { Customer } from '../customer';\nimport { Extension, ExtensionRegion } from '../extension';\nimport { FormField } from '../form';\nimport { Country } from '../geography';\nimport { Order } from '../order';\nimport { PaymentMethod } from '../payment';\nimport { PaymentProviderCustomer } from '../payment-provider-customer';\nimport { CardInstrument, PaymentInstrument } from '../payment/instrument';\nimport { Consignment, PickupOptionResult, SearchArea, ShippingOption } from '../shipping';\nimport { SignInEmail } from '../signin-email';\n\nimport Checkout from './checkout';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type Instrument = CardInstrument;\n\n/**\n * Responsible for getting the state of the current checkout.\n *\n * This object has a set of methods that allow you to get a specific piece of\n * checkout information, such as shipping and billing details.\n */\nexport default interface CheckoutStoreSelector {\n /**\n * Gets the current checkout.\n *\n * @returns The current checkout if it is loaded, otherwise undefined.\n */\n getCheckout(): Checkout | undefined;\n\n /**\n * Gets the current order.\n *\n * @returns The current order if it is loaded, otherwise undefined.\n */\n getOrder(): Order | undefined;\n\n /**\n * Gets the checkout configuration of a store.\n *\n * @returns The configuration object if it is loaded, otherwise undefined.\n */\n getConfig(): StoreConfig | undefined;\n\n /**\n * Gets the sign-in email.\n *\n * @returns The sign-in email object if sent, otherwise undefined\n */\n getSignInEmail(): SignInEmail | undefined;\n\n /**\n * Gets the shipping address of the current checkout.\n *\n * If the address is partially complete, it may not have shipping options\n * associated with it.\n *\n * @returns The shipping address object if it is loaded, otherwise\n * undefined.\n */\n getShippingAddress(): Address | undefined;\n\n /**\n * Gets a list of shipping options available for the shipping address.\n *\n * If there is no shipping address assigned to the current checkout, the\n * list of shipping options will be empty.\n *\n * @returns The list of shipping options if any, otherwise undefined.\n */\n getShippingOptions(): ShippingOption[] | undefined;\n\n /**\n * Gets a list of consignments.\n *\n * If there are no consignments created for to the current checkout, the\n * list will be empty.\n *\n * @returns The list of consignments if any, otherwise undefined.\n */\n getConsignments(): Consignment[] | undefined;\n\n /**\n * Gets the selected shipping option for the current checkout.\n *\n * @returns The shipping option object if there is a selected option,\n * otherwise undefined.\n */\n getSelectedShippingOption(): ShippingOption | undefined;\n\n /**\n * Gets a list of countries available for shipping.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getShippingCountries(): Country[] | undefined;\n\n /**\n * Gets the billing address of an order.\n *\n * @returns The billing address object if it is loaded, otherwise undefined.\n */\n getBillingAddress(): BillingAddress | undefined;\n\n /**\n * Gets a list of countries available for billing.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getBillingCountries(): Country[] | undefined;\n\n /**\n * Gets a list of payment methods available for checkout.\n *\n * @returns The list of payment methods if it is loaded, otherwise undefined.\n */\n getPaymentMethods(): PaymentMethod[] | undefined;\n\n /**\n * Gets a payment method by an id.\n *\n * The method returns undefined if unable to find a payment method with the\n * specified id, either because it is not available for the customer, or it\n * is not loaded.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns The payment method object if loaded and available, otherwise,\n * undefined.\n */\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n\n /**\n * Gets the payment method that is selected for checkout.\n *\n * @returns The payment method object if there is a selected method;\n * undefined if otherwise.\n */\n getSelectedPaymentMethod(): PaymentMethod | undefined;\n\n /**\n * Gets the available flash messages.\n *\n * Flash messages contain messages set by the server,\n * e.g: when trying to sign in using an invalid email link.\n *\n * @param type - The type of flash messages to be returned. Optional\n * @returns The flash messages if available, otherwise undefined.\n */\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n\n /**\n * Gets the current cart.\n *\n * @returns The current cart object if it is loaded, otherwise undefined.\n */\n getCart(): Cart | undefined;\n\n /**\n * Gets a list of coupons that are applied to the current checkout.\n *\n * @returns The list of applied coupons if there is any, otherwise undefined.\n */\n getCoupons(): Coupon[] | undefined;\n\n /**\n * Gets a list of gift certificates that are applied to the current checkout.\n *\n * @returns The list of applied gift certificates if there is any, otherwise undefined.\n */\n getGiftCertificates(): GiftCertificate[] | undefined;\n\n /**\n * Gets the current customer.\n *\n * @returns The current customer object if it is loaded, otherwise\n * undefined.\n */\n getCustomer(): Customer | undefined;\n\n /**\n * Checks if payment data is required or not.\n *\n * If payment data is required, customers should be prompted to enter their\n * payment details.\n *\n * ```js\n * if (state.checkout.isPaymentDataRequired()) {\n * // Render payment form\n * } else {\n * // Render \"Payment is not required for this order\" message\n * }\n * ```\n *\n * @param useStoreCredit - If true, check whether payment data is required\n * with store credit applied; otherwise, check without store credit.\n * @returns True if payment data is required, otherwise false.\n */\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n\n /**\n * Checks if payment data is submitted or not.\n *\n * If payment data is already submitted using a payment method, customers\n * should not be prompted to enter their payment details again.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns True if payment data is submitted, otherwise false.\n */\n isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean;\n\n /**\n * Gets a list of payment instruments associated with the current customer.\n *\n * @returns The list of payment instruments if it is loaded, otherwise undefined.\n */\n getInstruments(): Instrument[] | undefined;\n getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n\n /**\n * Gets a set of form fields that should be presented in order to create a customer.\n *\n * @returns The set of customer account form fields if it is loaded,\n * otherwise undefined.\n */\n getCustomerAccountFields(): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their billing address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of billing address form fields if it is loaded,\n * otherwise undefined.\n */\n getBillingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their shipping address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getShippingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a list of pickup options for specified parameters.\n *\n * @param consignmentId - Id of consignment.\n * @param searchArea - An object containing of radius and co-ordinates.\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n\n /**\n * Gets user experience settings.\n *\n * @returns The object of user experience settings if it is loaded, otherwise undefined.\n */\n getUserExperienceSettings(): UserExperienceSettings | undefined;\n\n /**\n * Gets a list of extensions available for checkout.\n *\n * @alpha\n * @returns The list of extensions if it is loaded, otherwise undefined.\n */\n getExtensions(): Extension[] | undefined;\n\n /**\n * Gets payment provider customers data.\n *\n * @alpha\n * @returns The object with payment provider customer data\n */\n getPaymentProviderCustomer(): PaymentProviderCustomer | undefined;\n\n /**\n * Gets the extension associated with a given region.\n *\n * @alpha\n * @param region - A checkout extension region.\n * @returns The extension corresponding to the specified region, otherwise undefined.\n */\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n}\n\nexport type CheckoutStoreSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreSelector;\n\nexport function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory {\n const getCheckout = createSelector(\n ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout,\n (getCheckout) => clone(getCheckout),\n );\n\n const getOrder = createSelector(\n ({ order }: InternalCheckoutSelectors) => order.getOrder,\n (getOrder) => clone(getOrder),\n );\n\n const getConfig = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) => clone(getStoreConfig),\n );\n\n const getShippingAddress = createSelector(\n ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getShippingAddress, getContextConfig) =>\n clone(() => {\n const shippingAddress = getShippingAddress();\n const context = getContextConfig();\n\n if (!shippingAddress) {\n if (!context || !context.geoCountryCode) {\n return;\n }\n\n return {\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return shippingAddress;\n }),\n );\n\n const getShippingOptions = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.availableShippingOptions;\n }),\n );\n\n const getConsignments = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) => clone(getConsignments),\n );\n\n const getSelectedShippingOption = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.selectedShippingOption;\n }),\n );\n\n const getShippingCountries = createSelector(\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingCountries) => clone(getShippingCountries),\n );\n\n const getBillingAddress = createSelector(\n ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getBillingAddress, getContextConfig) =>\n clone(() => {\n const billingAddress = getBillingAddress();\n const context = getContextConfig();\n const isEmptyBillingAddress =\n !billingAddress ||\n values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id')).every(\n (val) => !val || !val.length,\n );\n\n if (isEmptyBillingAddress) {\n if (!context || !context.geoCountryCode) {\n return billingAddress;\n }\n\n return {\n id: billingAddress ? billingAddress.id : '',\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n email: billingAddress ? billingAddress.email : '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return billingAddress;\n }),\n );\n\n const getBillingCountries = createSelector(\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getCountries) => clone(getCountries),\n );\n\n const getPaymentMethods = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods,\n (getPaymentMethods) => clone(getPaymentMethods),\n );\n\n const getPaymentMethod = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentMethod) => clone(getPaymentMethod),\n );\n\n const getSelectedPaymentMethod = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentId, getPaymentMethod) =>\n clone(() => {\n const payment = getPaymentId();\n\n return payment && getPaymentMethod(payment.providerId, payment.gatewayId);\n }),\n );\n\n const getCart = createSelector(\n ({ cart }: InternalCheckoutSelectors) => cart.getCart,\n (getCart) => clone(getCart),\n );\n\n const getCoupons = createSelector(\n ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons,\n (getCoupons) => clone(getCoupons),\n );\n\n const getGiftCertificates = createSelector(\n ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates,\n (getGiftCertificates) => clone(getGiftCertificates),\n );\n\n const getCustomer = createSelector(\n ({ customer }: InternalCheckoutSelectors) => customer.getCustomer,\n (getCustomer) => clone(getCustomer),\n );\n\n const getSignInEmail = createSelector(\n ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail,\n (getEmail) => clone(getEmail),\n );\n\n const isPaymentDataRequired = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired,\n (isPaymentDataRequired) => clone(isPaymentDataRequired),\n );\n\n const isPaymentDataSubmitted = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (isPaymentDataSubmitted, getPaymentMethod) =>\n clone((methodId: string, gatewayId?: string) => {\n return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId));\n }),\n );\n\n const getInstruments = createSelector(\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments,\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod,\n (getInstruments, getInstrumentsByPaymentMethod) => {\n function getInstrumentsSelector(): Instrument[] | undefined;\n function getInstrumentsSelector(\n paymentMethod: PaymentMethod,\n ): PaymentInstrument[] | undefined;\n\n function getInstrumentsSelector(\n paymentMethod?: PaymentMethod,\n ): PaymentInstrument[] | undefined {\n return paymentMethod\n ? getInstrumentsByPaymentMethod(paymentMethod)\n : getInstruments();\n }\n\n return clone(getInstrumentsSelector);\n },\n );\n\n const getCustomerAccountFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields,\n (getCustomerAccountFields) => clone(getCustomerAccountFields),\n );\n\n const getBillingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields,\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getBillingAddressFields, getCountries) =>\n clone((countryCode: string) => {\n return getBillingAddressFields(getCountries(), countryCode);\n }),\n );\n\n const getShippingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields,\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingAddressFields, getShippingCountries) =>\n clone((countryCode: string) => {\n return getShippingAddressFields(getShippingCountries(), countryCode);\n }),\n );\n\n const getFlashMessages = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getFlashMessages,\n (getFlashMessages) => clone(getFlashMessages),\n );\n\n const getPickupOptions = createSelector(\n ({ pickupOptions }: InternalCheckoutSelectors) => pickupOptions.getPickupOptions,\n (getPickupOptions) => clone(getPickupOptions),\n );\n\n const getUserExperienceSettings = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) =>\n clone(() => {\n const config = getStoreConfig();\n\n if (!config) {\n return;\n }\n\n return config.checkoutSettings.checkoutUserExperienceSettings;\n }),\n );\n\n const getExtensions = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensions,\n (getExtensions) => clone(getExtensions),\n );\n\n const getPaymentProviderCustomer = createSelector(\n ({ paymentProviderCustomer }: InternalCheckoutSelectors) =>\n paymentProviderCustomer.getPaymentProviderCustomer,\n (getPaymentProviderCustomer) => clone(getPaymentProviderCustomer),\n );\n\n const getExtensionByRegion = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensionByRegion,\n (getExtensionByRegion) => clone(getExtensionByRegion),\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreSelector => {\n return {\n getCheckout: getCheckout(state),\n getOrder: getOrder(state),\n getConfig: getConfig(state),\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getFlashMessages: getFlashMessages(state),\n getShippingAddress: getShippingAddress(state),\n getShippingOptions: getShippingOptions(state),\n getConsignments: getConsignments(state),\n getSelectedShippingOption: getSelectedShippingOption(state),\n getShippingCountries: getShippingCountries(state),\n getBillingAddress: getBillingAddress(state),\n getBillingCountries: getBillingCountries(state),\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethod: getPaymentMethod(state),\n getSelectedPaymentMethod: getSelectedPaymentMethod(state),\n getCart: getCart(state),\n getCoupons: getCoupons(state),\n getGiftCertificates: getGiftCertificates(state),\n getCustomer: getCustomer(state),\n isPaymentDataRequired: isPaymentDataRequired(state),\n isPaymentDataSubmitted: isPaymentDataSubmitted(state),\n getSignInEmail: getSignInEmail(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { CartChangedError, CartConsistencyError } from '../cart/errors';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for getting the error of any asynchronous checkout action, if\n * there is any.\n *\n * This object has a set of getters that would return an error if an action is\n * not executed successfully. For example, if you are unable to submit an order,\n * you can use this object to retrieve the reason for the failure.\n */\nexport default interface CheckoutStoreErrorSelector {\n getError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current checkout.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to update the current checkout.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to submit the current order.\n *\n * @returns The error object if unable to submit, otherwise undefined.\n */\n getSubmitOrderError(): Error | CartChangedError | CartConsistencyError | undefined;\n\n /**\n * Returns an error if unable to finalize the current order.\n *\n * @returns The error object if unable to finalize, otherwise undefined.\n */\n getFinalizeOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current order.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current cart.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCartError(): Error | undefined;\n\n /**\n * Returns an error if unable to load billing countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadBillingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load payment methods.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodsError(): Error | undefined;\n\n /**\n * Returns an error if unable to load a specific payment method.\n *\n * @param methodId - The identifier of the payment method to load.\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to initialize a specific payment method.\n *\n * @param methodId - The identifier of the payment method to initialize.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializePaymentError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to sign in.\n *\n * @returns The error object if unable to sign in, otherwise undefined.\n */\n getSignInError(): Error | undefined;\n\n /**\n * Returns an error if unable to sign out.\n *\n * @returns The error object if unable to sign out, otherwise undefined.\n */\n getSignOutError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the customer step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeCustomerError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping options.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to select a shipping option.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to select, otherwise undefined.\n */\n getSelectShippingOptionError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to continue as guest.\n *\n * The call could fail in scenarios where guest checkout is not allowed, for example, when existing accounts are required to sign-in.\n *\n * In the background, this call tries to set the billing address email using the Storefront API. You could access the Storefront API response status code using `getContinueAsGuestError` error selector.\n *\n * ```js\n * console.log(state.errors.getContinueAsGuestError());\n * console.log(state.errors.getContinueAsGuestError().status);\n * ```\n *\n * For more information about status codes, check [Checkout Storefront API - Add Checkout Billing Address](https://developer.bigcommerce.com/api-reference/cart-checkout/storefront-checkout-api/checkout-billing-address/checkoutsbillingaddressbycheckoutidpost).\n *\n * @returns The error object if unable to continue, otherwise undefined.\n */\n getContinueAsGuestError(): Error | undefined;\n\n /**\n * Returns an error if unable to update billing address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateBillingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to update subscriptions.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateSubscriptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to update shipping address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateShippingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to update a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to create consignments.\n *\n * @returns The error object if unable to create, otherwise undefined.\n */\n getCreateConsignmentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the shipping step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeShippingError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to apply store credit.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyStoreCreditError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a coupon code.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a coupon code.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a gift certificate.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a gift certificate.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to load payment instruments.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadInstrumentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a payment instrument.\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteInstrumentError(instrumentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load the checkout configuration of a store.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadConfigError(): Error | undefined;\n\n /**\n * Returns an error if unable to send sign-in email.\n *\n * @returns The error object if unable to send email, otherwise undefined.\n */\n getSignInEmailError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer account.\n *\n * @returns The error object if unable to create account, otherwise undefined.\n */\n getCreateCustomerAccountError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer address.\n *\n * @returns The error object if unable to create address, otherwise undefined.\n */\n getCreateCustomerAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch pickup options.\n *\n * @returns The error object if unable to fetch pickup options, otherwise undefined.\n */\n getPickupOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch extensions.\n *\n * @alpha\n * @returns The error object if unable to fetch extensions, otherwise undefined.\n */\n getLoadExtensionsError(): Error | undefined;\n}\n\nexport type CheckoutStoreErrorSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreErrorSelector;\n\nexport function createCheckoutStoreErrorSelectorFactory(): CheckoutStoreErrorSelectorFactory {\n const getError = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n for (const key of Object.keys(selector) as Array<\n keyof Omit\n >) {\n const error = selector[key]();\n\n if (error) {\n return error;\n }\n }\n },\n );\n\n const getSelectShippingOptionError = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.getSelectOptionError,\n ({ consignments }: InternalCheckoutSelectors) => consignments.getUpdateShippingOptionError,\n (getSelectOptionError, getUpdateShippingOptionError) => (consignmentId?: string) => {\n return getSelectOptionError() || getUpdateShippingOptionError(consignmentId);\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreErrorSelector => {\n const selector = {\n getLoadCheckoutError: state.checkout.getLoadError,\n getUpdateCheckoutError: state.checkout.getUpdateError,\n getSubmitOrderError: state.paymentStrategies.getExecuteError,\n getFinalizeOrderError: state.paymentStrategies.getFinalizeError,\n getLoadOrderError: state.order.getLoadError,\n getLoadCartError: state.cart.getLoadError,\n getLoadBillingCountriesError: state.countries.getLoadError,\n getLoadShippingCountriesError: state.shippingCountries.getLoadError,\n getLoadPaymentMethodsError: state.paymentMethods.getLoadError,\n getLoadPaymentMethodError: state.paymentMethods.getLoadMethodError,\n getInitializePaymentError: state.paymentStrategies.getInitializeError,\n getSignInError: state.customerStrategies.getSignInError,\n getSignOutError: state.customerStrategies.getSignOutError,\n getInitializeCustomerError: state.customerStrategies.getInitializeError,\n getLoadShippingOptionsError: state.consignments.getLoadShippingOptionsError,\n getSelectShippingOptionError: getSelectShippingOptionError(state),\n getContinueAsGuestError: state.billingAddress.getContinueAsGuestError,\n getUpdateBillingAddressError: state.billingAddress.getUpdateError,\n getUpdateSubscriptionsError: state.subscriptions.getUpdateError,\n getUpdateShippingAddressError: state.shippingStrategies.getUpdateAddressError,\n getDeleteConsignmentError: state.consignments.getDeleteError,\n getUpdateConsignmentError: state.consignments.getUpdateError,\n getCreateConsignmentsError: state.consignments.getCreateError,\n getInitializeShippingError: state.shippingStrategies.getInitializeError,\n getApplyStoreCreditError: state.storeCredit.getApplyError,\n getApplyCouponError: state.coupons.getApplyError,\n getRemoveCouponError: state.coupons.getRemoveError,\n getApplyGiftCertificateError: state.giftCertificates.getApplyError,\n getRemoveGiftCertificateError: state.giftCertificates.getRemoveError,\n getLoadInstrumentsError: state.instruments.getLoadError,\n getDeleteInstrumentError: state.instruments.getDeleteError,\n getLoadConfigError: state.config.getLoadError,\n getSignInEmailError: state.signInEmail.getSendError,\n getCreateCustomerAccountError: state.customer.getCreateAccountError,\n getCreateCustomerAddressError: state.customer.getCreateAddressError,\n getPickupOptionsError: state.pickupOptions.getLoadError,\n getLoadExtensionsError: state.extensions.getLoadError,\n };\n\n return {\n getError: getError(selector),\n ...selector,\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for checking the statuses of various asynchronous actions related\n * to checkout.\n *\n * This object has a set of getters that return true if an action is in\n * progress. For example, you can check whether a customer is submitting an\n * order and waiting for the request to complete.\n */\nexport default interface CheckoutStoreStatusSelector {\n /**\n * Checks whether any checkout action is pending.\n *\n * @returns True if there is a pending action, otherwise false.\n */\n isPending(): boolean;\n\n /**\n * Checks whether the current checkout is loading.\n *\n * @returns True if the current checkout is loading, otherwise false.\n */\n isLoadingCheckout(): boolean;\n\n /**\n * Checks whether the current checkout is being updated.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isUpdatingCheckout(): boolean;\n\n /**\n * Checks whether spam check is executing.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isExecutingSpamCheck(): boolean;\n\n /**\n * Checks whether the current order is submitting.\n *\n * @returns True if the current order is submitting, otherwise false.\n */\n isSubmittingOrder(): boolean;\n\n /**\n * Checks whether the current order is finalizing.\n *\n * @returns True if the current order is finalizing, otherwise false.\n */\n isFinalizingOrder(): boolean;\n\n /**\n * Checks whether the current order is loading.\n *\n * @returns True if the current order is loading, otherwise false.\n */\n isLoadingOrder(): boolean;\n\n /**\n * Checks whether the current cart is loading.\n *\n * @returns True if the current cart is loading, otherwise false.\n */\n isLoadingCart(): boolean;\n\n /**\n * Checks whether billing countries are loading.\n *\n * @returns True if billing countries are loading, otherwise false.\n */\n isLoadingBillingCountries(): boolean;\n\n /**\n * Checks whether shipping countries are loading.\n *\n * @returns True if shipping countries are loading, otherwise false.\n */\n isLoadingShippingCountries(): boolean;\n\n /**\n * Checks whether payment methods are loading.\n *\n * @returns True if payment methods are loading, otherwise false.\n */\n isLoadingPaymentMethods(): boolean;\n\n /**\n * Checks whether a specific or any payment method is loading.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is loading.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is loading, otherwise false.\n */\n isLoadingPaymentMethod(methodId?: string): boolean;\n\n /**\n * Checks whether a specific or any payment method is initializing.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is initializing.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is initializing, otherwise false.\n */\n isInitializingPayment(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing in.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing in using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing in the\n * current customer.\n * @returns True if the customer is signing in, otherwise false.\n */\n isSigningIn(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing out.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing out using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing out the\n * current customer.\n * @returns True if the customer is signing out, otherwise false.\n */\n isSigningOut(methodId?: string): boolean;\n\n /**\n * Checks whether the customer step is initializing.\n *\n * If an ID is provided, the method also checks whether the customer step is\n * initializing using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for initializing the\n * customer step of checkout.\n * @returns True if the customer step is initializing, otherwise false.\n */\n isInitializingCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether a wallet button is initialized.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the wallet button method is initialized, otherwise false.\n */\n isInitializedCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is executing payment method checkout.\n *\n * If an ID is provided, the method also checks whether the customer is\n * executing payment method checkout using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for continuing the\n * current customer.\n * @returns True if the customer is executing payment method checkout, otherwise false.\n */\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n\n /**\n * Checks whether shipping options are loading.\n *\n * @returns True if shipping options are loading, otherwise false.\n */\n isLoadingShippingOptions(): boolean;\n\n /**\n * Checks whether a shipping option is being selected.\n *\n * A consignment ID should be provided when checking if a shipping option\n * is being selected for a specific consignment, otherwise it will check\n * for all consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if selecting a shipping option, otherwise false.\n */\n isSelectingShippingOption(consignmentId?: string): boolean;\n\n /**\n * Checks whether the billing address is being updated.\n *\n * @returns True if updating their billing address, otherwise false.\n */\n isUpdatingBillingAddress(): boolean;\n\n /**\n * Checks whether the shopper is continuing out as a guest.\n *\n * @returns True if continuing as guest, otherwise false.\n */\n isContinuingAsGuest(): boolean;\n\n /**\n * Checks the shipping address is being updated.\n *\n * @returns True if updating their shipping address, otherwise false.\n */\n isUpdatingShippingAddress(): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if updating consignment(s), otherwise false.\n */\n isUpdatingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being deleted.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if deleting consignment(s), otherwise false.\n */\n isDeletingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @returns True if creating consignments, otherwise false.\n */\n isCreatingConsignments(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout process is initializing.\n *\n * If an identifier is provided, the method also checks whether the shipping\n * step is initializing using a specific shipping method with the same\n * identifier.\n *\n * @param methodId - The identifer of the initialization method to check.\n * @returns True if the shipping step is initializing, otherwise false.\n */\n isInitializingShipping(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is applying a coupon code.\n *\n * @returns True if applying a coupon code, otherwise false.\n */\n isApplyingCoupon(): boolean;\n\n /**\n * Checks whether the current customer is applying store credit.\n *\n * @returns True if applying store credit, otherwise false.\n */\n isApplyingStoreCredit(): boolean;\n\n /**\n * Checks whether the current customer is removing a coupon code.\n *\n * @returns True if removing a coupon code, otherwise false.\n */\n isRemovingCoupon(): boolean;\n\n /**\n * Checks whether a sign-in email is being sent.\n *\n * @returns True if sending a sign-in email, otherwise false\n */\n isSendingSignInEmail(): boolean;\n\n /**\n * Checks whether the current customer is applying a gift certificate.\n *\n * @returns True if applying a gift certificate, otherwise false.\n */\n isApplyingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer is removing a gift certificate.\n *\n * @returns True if removing a gift certificate, otherwise false.\n */\n isRemovingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer's payment instruments are loading.\n *\n * @returns True if payment instruments are loading, otherwise false.\n */\n isLoadingInstruments(): boolean;\n\n /**\n * Checks whether the current customer is deleting a payment instrument.\n *\n * @returns True if deleting a payment instrument, otherwise false.\n */\n isDeletingInstrument(instrumentId?: string): boolean;\n\n /**\n * Checks whether the checkout configuration of a store is loading.\n *\n * @returns True if the configuration is loading, otherwise false.\n */\n isLoadingConfig(): boolean;\n\n /**\n * Checks whether the customer step of a checkout is in a pending state.\n *\n * The customer step is considered to be pending if it is in the process of\n * initializing, signing in, signing out, and/or interacting with a customer\n * widget.\n *\n * @returns True if the customer step is pending, otherwise false.\n */\n isCustomerStepPending(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout is in a pending state.\n *\n * The shipping step is considered to be pending if it is in the process of\n * initializing, updating address, selecting a shipping option, and/or\n * interacting with a shipping widget.\n *\n * @returns True if the shipping step is pending, otherwise false.\n */\n isShippingStepPending(): boolean;\n\n /**\n * Checks whether the payment step of a checkout is in a pending state.\n *\n * The payment step is considered to be pending if it is in the process of\n * initializing, submitting an order, finalizing an order, and/or\n * interacting with a payment widget.\n *\n * @returns True if the payment step is pending, otherwise false.\n */\n isPaymentStepPending(): boolean;\n\n /**\n * Checks whether the subscriptions are being updated.\n *\n * @returns True if updating subscriptions, otherwise false.\n */\n isUpdatingSubscriptions(): boolean;\n\n /**\n * Checks whether a customer account is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAccount(): boolean;\n\n /**\n * Checks whether a customer address is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAddress(): boolean;\n\n /**\n * Checks whether pickup options are loading.\n *\n * @returns True if pickup options are loading, otherwise false.\n */\n isLoadingPickupOptions(): boolean;\n}\n\nexport type CheckoutStoreStatusSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreStatusSelector;\n\nexport function createCheckoutStoreStatusSelectorFactory(): CheckoutStoreStatusSelectorFactory {\n const isPending = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n return (\n Object.keys(selector) as Array>\n ).some((key) => selector[key]());\n },\n );\n\n const isSelectingShippingOption = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ consignments }: InternalCheckoutSelectors) => consignments.isUpdatingShippingOption,\n (isSelectingOption, isUpdatingShippingOption) => (consignmentId?: string) => {\n return isSelectingOption() || isUpdatingShippingOption(consignmentId);\n },\n );\n\n const isCustomerStepPending = createSelector(\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isInitializing,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningIn,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningOut,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isExecutingPaymentMethodCheckout,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isWidgetInteracting,\n (\n isInitializing,\n isSigningIn,\n isSigningOut,\n isExecutingPaymentMethodCheckout,\n isWidgetInteracting,\n ) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isSigningIn(methodId) ||\n isSigningOut(methodId) ||\n isExecutingPaymentMethodCheckout(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isShippingStepPending = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isInitializing,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isUpdatingAddress,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.isWidgetInteracting,\n (isInitializing, isUpdatingAddress, isSelectingOption, isWidgetInteracting) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isUpdatingAddress(methodId) ||\n isSelectingOption(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isPaymentStepPending = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isInitializing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isFinalizing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isWidgetInteracting,\n (isInitializing, isExecuting, isFinalizing, isWidgetInteracting) => (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isExecuting(methodId) ||\n isFinalizing(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isSubmittingOrder = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ checkout }: InternalCheckoutSelectors) => checkout.isExecutingSpamCheck, // Remove this when CheckoutService#initializeSpamProtection is deprecated\n (isExecuting, isExecutingSpamCheck) => (methodId?: string) => {\n return isExecuting(methodId) || isExecutingSpamCheck();\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreStatusSelector => {\n const selector = {\n isLoadingCheckout: state.checkout.isLoading,\n isUpdatingCheckout: state.checkout.isUpdating,\n isExecutingSpamCheck: state.checkout.isExecutingSpamCheck,\n isSubmittingOrder: isSubmittingOrder(state),\n isFinalizingOrder: state.paymentStrategies.isFinalizing,\n isLoadingOrder: state.order.isLoading,\n isLoadingCart: state.cart.isLoading,\n isLoadingBillingCountries: state.countries.isLoading,\n isLoadingShippingCountries: state.shippingCountries.isLoading,\n isLoadingPaymentMethods: state.paymentMethods.isLoading,\n isLoadingPaymentMethod: state.paymentMethods.isLoadingMethod,\n isInitializingPayment: state.paymentStrategies.isInitializing,\n isSigningIn: state.customerStrategies.isSigningIn,\n isSigningOut: state.customerStrategies.isSigningOut,\n isExecutingPaymentMethodCheckout:\n state.customerStrategies.isExecutingPaymentMethodCheckout,\n isInitializingCustomer: state.customerStrategies.isInitializing,\n isInitializedCustomer: state.customerStrategies.isInitialized,\n isLoadingShippingOptions: state.consignments.isLoadingShippingOptions,\n isSelectingShippingOption: isSelectingShippingOption(state),\n isUpdatingBillingAddress: state.billingAddress.isUpdating,\n isUpdatingSubscriptions: state.subscriptions.isUpdating,\n isCreatingCustomerAccount: state.customer.isCreatingCustomerAccount,\n isCreatingCustomerAddress: state.customer.isCreatingCustomerAddress,\n isContinuingAsGuest: state.billingAddress.isContinuingAsGuest,\n isUpdatingShippingAddress: state.shippingStrategies.isUpdatingAddress,\n isUpdatingConsignment: state.consignments.isUpdating,\n isDeletingConsignment: state.consignments.isDeleting,\n isCreatingConsignments: state.consignments.isCreating,\n isInitializingShipping: state.shippingStrategies.isInitializing,\n isApplyingStoreCredit: state.storeCredit.isApplying,\n isApplyingCoupon: state.coupons.isApplying,\n isRemovingCoupon: state.coupons.isRemoving,\n isApplyingGiftCertificate: state.giftCertificates.isApplying,\n isRemovingGiftCertificate: state.giftCertificates.isRemoving,\n isLoadingInstruments: state.instruments.isLoading,\n isDeletingInstrument: state.instruments.isDeleting,\n isLoadingConfig: state.config.isLoading,\n isSendingSignInEmail: state.signInEmail.isSending,\n isCustomerStepPending: isCustomerStepPending(state),\n isShippingStepPending: isShippingStepPending(state),\n isPaymentStepPending: isPaymentStepPending(state),\n isLoadingPickupOptions: state.pickupOptions.isLoading,\n };\n\n return {\n isPending: isPending(selector),\n ...selector,\n };\n });\n}\n","import {\n CheckoutSelectors,\n createCheckoutStoreErrorSelectorFactory,\n createCheckoutStoreSelectorFactory,\n createCheckoutStoreStatusSelectorFactory,\n InternalCheckoutSelectors,\n} from '../checkout';\n\nexport type CheckoutSelectorsFactory = (selectors: InternalCheckoutSelectors) => CheckoutSelectors;\n\nexport function createCheckoutSelectorsFactory(): CheckoutSelectorsFactory {\n const createCheckoutStoreSelector = createCheckoutStoreSelectorFactory();\n const createCheckoutStoreErrorSelector = createCheckoutStoreErrorSelectorFactory();\n const createCheckoutStoreStatusSelector = createCheckoutStoreStatusSelectorFactory();\n\n return (selectors: InternalCheckoutSelectors) => {\n const data = createCheckoutStoreSelector(selectors);\n const errors = createCheckoutStoreErrorSelector(selectors);\n const statuses = createCheckoutStoreStatusSelector(selectors);\n\n return {\n data,\n errors,\n statuses,\n };\n };\n}\n\nexport default function createCheckoutSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutSelectors {\n return createCheckoutSelectorsFactory()(selectors);\n}\n","import { CheckoutSelectors } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\n\nimport { ExtensionEventBroadcaster } from './extension-event-broadcaster';\nimport { ExtensionEventType } from './extension-events';\nimport { ExtensionMessenger } from './extension-messenger';\nimport { subscribeConsignmentsChange } from './subscribers';\n\nexport function createExtensionEventBroadcaster(\n store: DataStoreProjection,\n messenger: ExtensionMessenger,\n): ExtensionEventBroadcaster {\n const subscribers = {\n [ExtensionEventType.ConsignmentsChanged]: subscribeConsignmentsChange,\n };\n\n return new ExtensionEventBroadcaster(store, messenger, subscribers);\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport {\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from '../payment/strategies/braintree';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createCustomerStrategyRegistryV2 from './create-customer-strategy-registry-v2';\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport CustomerStrategyActionCreator from './customer-strategy-action-creator';\nimport { CustomerStrategy } from './strategies';\nimport { BraintreeVisaCheckoutCustomerStrategy } from './strategies/braintree';\nimport { DefaultCustomerStrategy } from './strategies/default';\nimport { MasterpassCustomerStrategy } from './strategies/masterpass';\nimport { SquareCustomerStrategy } from './strategies/square';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n locale: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const formPoster = createFormPoster();\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n createSpamProtection(scriptLoader),\n new SpamProtectionRequestSender(requestSender),\n );\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n );\n\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n\n registry.register(\n 'braintreevisacheckout',\n () =>\n new BraintreeVisaCheckoutCustomerStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n new CustomerStrategyActionCreator(registry, customerRegistryV2),\n remoteCheckoutActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n formPoster,\n ),\n );\n\n registry.register(\n 'squarev2',\n () =>\n new SquareCustomerStrategy(\n store,\n new RemoteCheckoutActionCreator(remoteCheckoutRequestSender, checkoutActionCreator),\n ),\n );\n\n registry.register(\n 'masterpass',\n () =>\n new MasterpassCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register('default', () => new DefaultCustomerStrategy(store, customerActionCreator));\n\n return registry;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader, getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { StorefrontPaymentRequestSender } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport {\n createSpamProtection,\n GoogleRecaptcha,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createPaymentStrategyRegistryV2 from './create-payment-strategy-registry-v2';\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentMethodActionCreator from './payment-method-action-creator';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyActionCreator from './payment-strategy-action-creator';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { BarclaysPaymentStrategy } from './strategies/barclays';\nimport { BNZPaymentStrategy } from './strategies/bnz';\nimport {\n BraintreeCreditCardPaymentStrategy,\n BraintreeVenmoPaymentStrategy,\n BraintreeVisaCheckoutPaymentStrategy,\n createBraintreePaymentProcessor,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from './strategies/braintree';\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlowV2,\n} from './strategies/cardinal';\nimport { CBAMPGSPaymentStrategy, CBAMPGSScriptLoader } from './strategies/cba-mpgs';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport { MasterpassPaymentStrategy, MasterpassScriptLoader } from './strategies/masterpass';\nimport { OpyPaymentStrategy, OpyScriptLoader } from './strategies/opy';\nimport { PaypalExpressPaymentStrategy, PaypalScriptLoader } from './strategies/paypal';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\nimport { WepayPaymentStrategy, WepayRiskClient } from './strategies/wepay';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n spamProtection: GoogleRecaptcha,\n locale: string,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n const scriptLoader = getScriptLoader();\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(paymentIntegrationService);\n const braintreePaymentProcessor = createBraintreePaymentProcessor(scriptLoader);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n new SpamProtectionRequestSender(requestSender),\n );\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n checkoutValidator,\n );\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n const paymentActionCreator = new PaymentActionCreator(\n paymentRequestSender,\n orderActionCreator,\n paymentRequestTransformer,\n paymentHumanVerificationHandler,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentStrategyActionCreator = new PaymentStrategyActionCreator(\n registry,\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n );\n const formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n registry.register(\n PaymentStrategyType.BARCLAYS,\n () =>\n new BarclaysPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE,\n () =>\n new BraintreeCreditCardPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), window),\n window,\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VISA_CHECKOUT,\n () =>\n new BraintreeVisaCheckoutPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CBA_MPGS,\n () =>\n new CBAMPGSPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n paymentMethodActionCreator,\n new CBAMPGSScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CONVERGE,\n () =>\n new ConvergePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ,\n () =>\n new BNZPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.MASTERPASS,\n () =>\n new MasterpassPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.OPY,\n () =>\n new OpyPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n new OpyScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS_CREDIT,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PPSDK,\n () =>\n new PPSDKStrategy(\n store,\n orderActionCreator,\n createSubStrategyRegistry(\n store,\n orderActionCreator,\n requestSender,\n stepHandler,\n hostedFormFactory,\n ),\n new PaymentResumer(requestSender, stepHandler),\n new BrowserStorage('PPSDK'),\n ),\n );\n\n registry.register(\n PaymentStrategyType.WE_PAY,\n () =>\n new WepayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n return registry;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport default function createBraintreePaymentProcessor(scriptLoader: ScriptLoader) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, window);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n const braintreeHostedForm = new BraintreeHostedForm(braintreeSDKCreator);\n\n return new BraintreePaymentProcessor(braintreeSDKCreator, braintreeHostedForm);\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport ConsignmentActionCreator from './consignment-action-creator';\nimport ConsignmentRequestSender from './consignment-request-sender';\nimport ShippingStrategyActionCreator from './shipping-strategy-action-creator';\nimport { ShippingStrategy } from './strategies';\nimport { AmazonPayV2ShippingStrategy } from './strategies/amazon-pay-v2';\nimport { BraintreeFastlaneShippingStrategy } from './strategies/braintree';\nimport { DefaultShippingStrategy } from './strategies/default';\nimport { PayPalCommerceFastlaneShippingStrategy } from './strategies/paypal-commerce';\nimport { StripeUPEShippingStrategy } from './strategies/stripe-upe';\n\nexport default function createShippingStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n): Registry {\n const registry = new Registry();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const consignmentRequestSender = new ConsignmentRequestSender(requestSender);\n const consignmentActionCreator = new ConsignmentActionCreator(\n consignmentRequestSender,\n checkoutRequestSender,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const scriptLoader = getScriptLoader();\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n );\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2ShippingStrategy(\n store,\n consignmentActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n createAmazonPayV2PaymentProcessor(),\n new ShippingStrategyActionCreator(registry),\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPEShippingStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n consignmentActionCreator,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n 'braintreeacceleratedcheckout',\n () =>\n new BraintreeFastlaneShippingStrategy(\n store,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n new PaymentProviderCustomerActionCreator(),\n new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n ),\n ),\n );\n\n registry.register(\n 'paypalcommerceacceleratedcheckout',\n () =>\n new PayPalCommerceFastlaneShippingStrategy(\n store,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n new PaymentProviderCustomerActionCreator(),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\n}\n","export interface RootCacheKeyMap {\n maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n maps: ChildCacheKeyMap[];\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n usedCount: number;\n value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'parentMap');\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport {\n ChildCacheKeyMap,\n IntermediateCacheKeyMap,\n isRootCacheKeyMap,\n isTerminalCacheKeyMap,\n RootCacheKeyMap,\n TerminalCacheKeyMap,\n} from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n maxSize?: number;\n onExpire?(key: string): void;\n isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n index: number;\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n private _lastId = 0;\n private _map: RootCacheKeyMap = { maps: [] };\n private _usedMaps: TerminalCacheKeyMap[] = [];\n private _options: Required;\n\n constructor(options?: CacheKeyResolverOptions) {\n this._options = {\n maxSize: 0,\n isEqual: shallowEqual,\n onExpire: noop,\n ...options,\n };\n }\n\n getKey(...args: any[]): string {\n const result = this._resolveMap(...args);\n const { index, parentMap } = result;\n let { map } = result;\n\n if (map && map.cacheKey) {\n map.usedCount++;\n } else {\n map = this._generateMap(parentMap, args.slice(index));\n }\n\n // Keep track of the least used map so we can remove it if the size of\n // the stack exceeds the maximum size.\n this._removeLeastUsedMap(map);\n\n return map.cacheKey;\n }\n\n getUsedCount(...args: any[]): number {\n const { map } = this._resolveMap(...args);\n\n return map ? map.usedCount : 0;\n }\n\n private _resolveMap(...args: any[]): ResolveResult {\n let index = 0;\n let parentMap = this._map;\n\n // Traverse the tree to find the linked list of maps that match the\n // arguments of the call. Each intermediate or terminal map contains a\n // value that could be used to match with the arguments. The last map in\n // the list (the terminal) should contain a cache key. If it can does\n // not exist, we will return a falsy value so that the caller could\n // handle and generate a new cache key.\n while (parentMap.maps.length) {\n let isMatched = false;\n\n for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n const map = parentMap.maps[mapIndex];\n\n if (!this._options.isEqual(map.value, args[index])) {\n continue;\n }\n\n // Move the most recently used map to the top of the stack for\n // quicker access\n parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n if (\n (args.length === 0 || index === args.length - 1) &&\n isTerminalCacheKeyMap(map)\n ) {\n return { index, map, parentMap };\n }\n\n isMatched = true;\n parentMap = map;\n index++;\n\n break;\n }\n\n if (!isMatched) {\n break;\n }\n }\n\n return { index, parentMap };\n }\n\n private _generateMap(\n parent: RootCacheKeyMap | IntermediateCacheKeyMap,\n args: any[],\n ): TerminalCacheKeyMap {\n let index = 0;\n let parentMap = parent;\n let map: IntermediateCacheKeyMap;\n\n do {\n map = {\n maps: [],\n parentMap,\n usedCount: 1,\n value: args[index],\n };\n\n // Continue to build the tree of maps so that it could be resolved\n // next time when the function is called with the same set of\n // arguments.\n parentMap.maps.unshift(map);\n\n parentMap = map;\n index++;\n } while (index < args.length);\n\n const terminalMap = map as TerminalCacheKeyMap;\n\n terminalMap.cacheKey = `${++this._lastId}`;\n\n return terminalMap;\n }\n\n private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n if (!this._options.maxSize) {\n return;\n }\n\n const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n this._usedMaps.splice(index === -1 ? 0 : index, index === -1 ? 0 : 1, recentlyUsedMap);\n\n if (this._usedMaps.length <= this._options.maxSize) {\n return;\n }\n\n const map = this._usedMaps.pop();\n\n if (!map) {\n return;\n }\n\n this._removeMap(map);\n this._options.onExpire(map.cacheKey);\n }\n\n private _removeMap(map: ChildCacheKeyMap): void {\n if (!map.parentMap) {\n return;\n }\n\n map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n if (isRootCacheKeyMap(map.parentMap)) {\n return;\n }\n\n this._removeMap(map.parentMap);\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\n\nimport { bindDecorator } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CacheKeyResolver, isEqual, isPrivate } from '../utility';\n\n/**\n * Decorates a class by patching all of its methods to cache their return values\n * and return them if they are called again with the same set of parameters. The\n * decorator also binds all the methods to the calling instance so it can be\n * destructed.\n */\nexport default function selectorDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n selectorMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\nfunction selectorMethodDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let resolver = new CacheKeyResolver();\n let method = descriptor.value;\n let memoizedMethod = memoize(method);\n\n return bindDecorator(target, key, {\n get() {\n const value = ((...args: any[]) => {\n const cachedValue = memoizedMethod.call(this, ...args);\n\n if (resolver.getUsedCount(...args) === 1) {\n return cachedValue;\n }\n\n const newValue = method.call(this, ...args);\n\n if (isEqual(newValue, cachedValue, { keyFilter: (key) => !isPrivate(key) })) {\n return cachedValue;\n }\n\n memoizedMethod.cache.set(resolver.getKey(...args), newValue);\n\n return newValue;\n }) as T;\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n set(value) {\n resolver = new CacheKeyResolver();\n method = value;\n memoizedMethod = memoize(method);\n },\n });\n}\n\nexport type Constructor = new (...args: any[]) => T;\ntype Method = (...args: any[]) => any;\n","export default function isPrivate(key: string): boolean {\n return `${key}`.indexOf('$$') === 0 || `${key}`.indexOf('_') === 0;\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonErrorSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n getInitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getInitializeError(methodId);\n }\n\n getDeinitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getDeinitializeError(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonStatusSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n isInitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isInitializing(methodId);\n }\n\n isDeinitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isDeinitializing(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\n\nimport CheckoutButtonErrorSelector from './checkout-button-error-selector';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStatusSelector from './checkout-button-status-selector';\n\nexport default function createCheckoutButtonSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutButtonSelectors {\n const errors = new CheckoutButtonErrorSelector(selectors);\n const statuses = new CheckoutButtonStatusSelector(selectors);\n\n return {\n errors,\n statuses,\n };\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../checkout';\nimport { isElementId, setUniqueElementId } from '../common/dom';\n\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonSelectors from './create-checkout-button-selectors';\n\n@bind\nexport default class CheckoutButtonInitializer {\n private _state: CheckoutButtonSelectors;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _buttonStrategyActionCreator: CheckoutButtonStrategyActionCreator,\n ) {\n this._state = createCheckoutButtonSelectors(this._store.getState());\n\n this._store.subscribe((state) => {\n this._state = createCheckoutButtonSelectors(state);\n });\n }\n\n /**\n * Returns a snapshot of the current state.\n *\n * The method returns a new instance every time there is a change in the\n * state. You can query the state by calling any of its getter methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.errors.getInitializeButtonError());\n * console.log(state.statuses.isInitializingButton());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutButtonSelectors {\n return this._state;\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the current state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.statuses.isInitializingButton());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.errors.getInitializeButtonError();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.errors.getInitializeButtonError())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutButtonSelectors) => void,\n ...filters: Array<(state: CheckoutButtonSelectors) => any>\n ): () => void {\n return this._store.subscribe(\n () => subscriber(this.getState()),\n (state) => state.checkoutButton.getState(),\n ...filters.map(\n (filter) => (state: InternalCheckoutSelectors) =>\n filter(createCheckoutButtonSelectors(state)),\n ),\n );\n }\n\n /**\n * Initializes the checkout button of a payment method.\n *\n * When the checkout button is initialized, it will be inserted into the DOM,\n * ready to be interacted with by the customer.\n *\n * ```js\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * containerId: 'checkoutButton',\n * braintreepaypal: {\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n initializeButton(options: CheckoutButtonInitializeOptions): Promise {\n const containerIds = isElementId(options.containerId)\n ? [options.containerId]\n : setUniqueElementId(options.containerId, `${options.methodId}-container`);\n\n return Promise.all(\n containerIds.map((containerId) => {\n const action = this._buttonStrategyActionCreator.initialize({\n ...options,\n containerId,\n });\n const queueId = `checkoutButtonStrategy:${options.methodId}:${containerId}`;\n\n return this._store.dispatch(action, { queueId });\n }),\n ).then(() => this.getState());\n }\n\n /**\n * De-initializes the checkout button by performing any necessary clean-ups.\n *\n * ```js\n * await service.deinitializeButton({\n * methodId: 'braintreepaypal',\n * });\n * ```\n *\n * @param options - Options for deinitializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n deinitializeButton(options: CheckoutButtonOptions): Promise {\n const action = this._buttonStrategyActionCreator.deinitialize(options);\n const queueId = `checkoutButtonStrategy:${options.methodId}`;\n\n return this._store.dispatch(action, { queueId }).then(() => this.getState());\n }\n}\n","/* eslint-disable no-useless-escape */\nexport default function isElementId(id: string): boolean {\n return /^\\w[\\w\\-\\:\\.]*$/.test(id);\n}\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nexport default function setUniqueElementId(selector: string, idPrefix: string): string[] {\n const containers = document.querySelectorAll(selector);\n\n if (!containers.length) {\n throw new InvalidArgumentError(\n `Unable to find any element with the specified selector: ${selector}`,\n );\n }\n\n return Array.prototype.slice.call(containers).map((container: HTMLElement) => {\n if (!container.id) {\n container.id = uniqueId(idPrefix);\n }\n\n return container.id;\n });\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutButtonStrategy as CheckoutButtonStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator } from '../payment';\n\nimport {\n CheckoutButtonActionType,\n DeinitializeButtonAction,\n InitializeButtonAction,\n} from './checkout-button-actions';\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonRegistryV2 from './checkout-button-strategy-registry-v2';\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\n\nexport default class CheckoutButtonStrategyActionCreator {\n constructor(\n private _registry: Registry,\n private _registryV2: CheckoutButtonRegistryV2,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n initialize(\n options: CheckoutButtonInitializeOptions,\n ): ThunkAction {\n return (store) => {\n const meta = {\n methodId: options.methodId,\n containerId: options.containerId,\n };\n\n if (\n store.getState().checkoutButton.isInitialized(options.methodId, options.containerId)\n ) {\n return empty();\n }\n\n const paymentMethodRequestParams = options.currencyCode\n ? { params: { currencyCode: options.currencyCode } }\n : {};\n\n const paymentMethodRequestOptions = {\n ...paymentMethodRequestParams,\n timeout: options.timeout,\n useCache: true,\n };\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.InitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n this._paymentMethodActionCreator.loadPaymentMethod(\n options.methodId,\n paymentMethodRequestOptions,\n )(store),\n defer(() =>\n this._getStrategy(options.methodId)\n .initialize(options)\n .then(() =>\n createAction(\n CheckoutButtonActionType.InitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutButtonActionType.InitializeButtonFailed, error, meta),\n ),\n );\n };\n }\n\n deinitialize(\n options: CheckoutButtonOptions,\n ): ThunkAction {\n return (store) => {\n const meta = { methodId: options.methodId };\n\n if (!store.getState().checkoutButton.isInitialized(options.methodId)) {\n return empty();\n }\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.DeinitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n defer(() =>\n this._getStrategy(options.methodId)\n .deinitialize()\n .then(() =>\n createAction(\n CheckoutButtonActionType.DeinitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n CheckoutButtonActionType.DeinitializeButtonFailed,\n error,\n meta,\n ),\n ),\n );\n };\n }\n\n private _getStrategy(\n methodId: CheckoutButtonMethodType,\n ): CheckoutButtonStrategy | CheckoutButtonStrategyV2 {\n let strategy: CheckoutButtonStrategy | CheckoutButtonStrategyV2;\n\n try {\n strategy = this._registryV2.get({ id: methodId });\n } catch {\n strategy = this._registry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","import { Address } from '../../../address';\n\nimport { BraintreeShippingAddressOverride } from './braintree';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '../../../payment/strategies/paypal';\n\nexport default function getValidButtonStyle(style: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height, layout, shape, size, tagline } = style;\n\n const validStyles = {\n color,\n fundingicons,\n height: getValidHeight(height),\n layout,\n shape: shape || 'rect',\n size,\n tagline,\n };\n\n return omitBy(validStyles, isNil);\n}\n\nfunction getValidHeight(height?: number): number {\n const minHeight = 25;\n const maxHeight = 55;\n\n if (typeof height !== 'number' || height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport isBraintreeError from '../../../payment/strategies/braintree/is-braintree-error';\nimport { PaypalAuthorizeData, PaypalHostWindow } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalButtonInitializeOptions } from './braintree-paypal-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypal, containerId, methodId } = options;\n const { messagingContainerId, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this._renderPayPalComponents(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, messagingContainerId, onError);\n\n this._braintreeSDKCreator.initialize(clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalComponents(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { messagingContainerId } = braintreepaypal;\n\n this._renderPayPalMessages(messagingContainerId);\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n testMode,\n );\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError, onEligibilityFailure } =\n braintreepaypal;\n const { paypal } = this._window;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const validButtonStyle = style ? getValidButtonStyle(style) : {};\n\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: validButtonStyle,\n createOrder: () =>\n this._setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n }\n } else {\n this._removeElement(containerId);\n }\n }\n\n private _renderPayPalMessages(messagingContainerId?: string): void {\n const isMessageContainerAvailable =\n messagingContainerId && Boolean(document.getElementById(messagingContainerId));\n const { paypal } = this._window;\n\n if (paypal && isMessageContainerAvailable) {\n const { checkout } = this._store.getState();\n const grandTotal = checkout.getCheckoutOrThrow().outstandingBalance;\n\n const paypalMessagesRender = paypal.Messages({\n amount: grandTotal,\n placement: 'cart',\n });\n\n paypalMessagesRender.render(`#${messagingContainerId}`);\n } else {\n this._removeElement(messagingContainerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { buyNowInitializeOptions, shippingAddress, onPaymentError } = braintreepaypal;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypal.currencyCode ?? state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onPaymentError(error);\n }\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onError(error);\n }\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n buttonContainerId: string,\n messagingContainerId?: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(buttonContainerId);\n this._removeElement(messagingContainerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","export interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface MessagesStyleOptions {\n layout?: 'text' | 'flex';\n logo?: {\n type: 'none' | 'inline' | 'primary';\n };\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onClick?(): void;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n WHITE = 'white',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport isBraintreeError from '../../../payment/strategies/braintree/is-braintree-error';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalCreditButtonInitializeOptions } from './braintree-paypal-credit-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalCreditButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypalcredit, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypalcredit.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypalcredit.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, braintreepaypalcredit.onError);\n\n this._braintreeSDKCreator.initialize(clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError, onEligibilityFailure } =\n braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = style ? getValidButtonStyle(style) : {};\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n } else if (\n paypal.FUNDING.CREDIT &&\n onEligibilityFailure &&\n typeof onEligibilityFailure === 'function'\n ) {\n // the condition is related to paypal.FUNDING.CREDIT because when paypal.FUNDING.PAYLATER is not eligible then\n // CREDIT button should be configured and triggered to render with eligibility check\n // and if it is not eligible, then onEligibilityFailure callback should be called\n onEligibilityFailure();\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(containerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypalcredit;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypalcredit.currencyCode ??\n state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onPaymentError(error);\n }\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onError(error);\n }\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n containerId: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(containerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport {\n formatLocale,\n getCallbackUrl,\n Masterpass,\n MasterpassCheckoutOptions,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class MasterpassButtonStrategy implements CheckoutButtonStrategy {\n private _masterpassClient?: Masterpass;\n private _methodId?: string;\n private _signInButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n this._methodId = methodId;\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: paymentMethod.config.testMode,\n checkoutId: paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader.load(masterpassScriptLoaderParams);\n })\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n this._signInButton = this._createSignInButton(containerId);\n });\n }\n\n deinitialize(): Promise {\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.removeEventListener('click', this._handleWalletButtonClick);\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const buttonContainer = document.getElementById(containerId);\n const state = this._store.getState();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n const storeConfig = state.config.getStoreConfig();\n\n if (!buttonContainer) {\n throw new Error('Need a container to place the button');\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new InvalidArgumentError('Unable to retrieve store configuration');\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n buttonContainer.appendChild(button);\n\n button.addEventListener('click', this._handleWalletButtonClick);\n\n return button;\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: paymentMethod.initializationData.checkoutId,\n allowedCardTypes: paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.cart.cartAmount.toString(),\n currency: checkout.cart.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('cart'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(): void {\n if (!this._masterpassClient) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n this._masterpassClient.checkout(this._createMasterpassPayload());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport { INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod } from '../../../payment';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalScriptLoader,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paypalScriptLoader: PaypalScriptLoader,\n private _formPoster: FormPoster,\n private _host: string = '',\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const paypalOptions = options.paypal;\n const state = this._store.getState();\n const paymentMethod = (this._paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n ));\n\n if (!paypalOptions) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._paypalScriptLoader\n .loadPaypal(paymentMethod.config.merchantId)\n .then((paypal) => {\n if (!paymentMethod || !paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: paypalOptions.clientId };\n\n const fundingCreditOption = paypal.FUNDING.CREDIT || 'credit';\n const allowedSources = paypalOptions.allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !paypalOptions.allowCredit ? [fundingCreditOption] : [];\n\n return paypal.Button.render(\n {\n env,\n client: clientToken,\n commit: paypalOptions.shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: {\n shape: PaypalButtonStyleShapeOption.RECT,\n ...pick(\n paypalOptions.style,\n 'layout',\n 'color',\n 'label',\n 'shape',\n 'tagline',\n 'fundingicons',\n ),\n size:\n paymentMethod.id === 'paypalexpress' &&\n paypalOptions.style?.size === 'small'\n ? PaypalButtonStyleSizeOption.RESPONSIVE\n : paypalOptions.style?.size,\n },\n payment: (_, actions) =>\n this._setupPayment(merchantId, actions, paypalOptions.onPaymentError),\n onAuthorize: (data, actions) =>\n this._tokenizePayment(\n data,\n actions,\n paypalOptions.shouldProcessPayment,\n paypalOptions.onAuthorizeError,\n ),\n },\n options.containerId,\n );\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return Promise.resolve();\n }\n\n private _setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const cart = state.cart.getCart();\n const cartId = cart ? cart.id : '';\n\n return actions.request.post(\n `${this._host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n })\n .then((res) => res.id)\n .catch((error) => {\n if (onError) {\n onError(error);\n }\n\n throw error;\n });\n }\n\n private _tokenizePayment(\n data: PaypalAuthorizeData,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n _onError?: (error: StandardError) => void, // FIXME: This parameter seems to be unused\n ): Promise {\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const methodId = this._paymentMethod.id;\n\n return actions.payment.get(data.paymentID).then((payload) => {\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(payload.payer.payer_info),\n });\n });\n }\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class AmazonPayV2ConfigCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during config creation process. Please try again later.',\n );\n\n this.name = 'AmazonPayV2ConfigCreationError';\n this.type = 'amazon_pay_v2_config_creation_error';\n }\n}\n","import { WithBuyNowFeature } from './amazon-pay-v2-button-options';\n\nexport function isWithBuyNowFeatures(options: unknown): options is WithBuyNowFeature {\n if (!(options instanceof Object)) {\n return false;\n }\n\n return 'buyNowInitializeOptions' in options;\n}\n","import {\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BuyNowCartCreationError,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n getShippableItemsCount,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n WithAmazonPayV2ButtonInitializeOptions,\n WithBuyNowFeature,\n} from './amazon-pay-v2-button-options';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\nimport AmazonPayV2ConfigCreationError from './errors/amazon-pay-v2-config-creation-error';\nimport { isWithBuyNowFeatures } from './isWithBuyNowFeatures';\n\nexport default class AmazonPayV2ButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowInitializeOptions: WithBuyNowFeature['buyNowInitializeOptions'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private amazonPayV2ConfigRequestSender: AmazonPayV2RequestSender,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithAmazonPayV2ButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, amazonpay } = options;\n const { buttonColor } = amazonpay || {};\n\n if (!methodId || !containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (!amazonpay) {\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n const initializeAmazonButtonOptions = isWithBuyNowFeatures(amazonpay)\n ? undefined\n : amazonpay;\n\n if (\n isWithBuyNowFeatures(amazonpay) &&\n typeof amazonpay.buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ) {\n this._buyNowInitializeOptions = amazonpay.buyNowInitializeOptions;\n this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(true);\n }\n\n this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this.paymentIntegrationService.getState(),\n containerId,\n methodId,\n options: initializeAmazonButtonOptions,\n placement: AmazonPayV2Placement.Cart,\n buttonColor,\n isButtonMicroTextDisabled: initializationData?.isButtonMicroTextDisabled,\n });\n\n if (this._buyNowInitializeOptions) {\n this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(\n this._getCheckoutCreationRequestConfig.bind(this),\n );\n }\n }\n\n deinitialize(): Promise {\n return this.amazonPayV2PaymentProcessor.deinitialize();\n }\n\n private async _createBuyNowCartOrThrow() {\n const buyNowCartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!buyNowCartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const buyNowCart = await this.paymentIntegrationService.createBuyNowCart(\n buyNowCartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private async _createCheckoutConfig(\n id: string,\n ): Promise> {\n try {\n const {\n body: { payload, public_key, ...rest },\n } = await this.amazonPayV2ConfigRequestSender.createCheckoutConfig(id);\n\n return {\n payloadJSON: payload,\n publicKeyId: public_key,\n ...rest,\n };\n } catch (error) {\n throw new AmazonPayV2ConfigCreationError();\n }\n }\n\n private async _getCheckoutCreationRequestConfig() {\n const buyNowCart = await this._createBuyNowCartOrThrow();\n const estimatedOrderAmount = {\n amount: String(buyNowCart.baseAmount),\n currencyCode: buyNowCart.currency.code,\n };\n const createCheckoutSessionConfig = await this._createCheckoutConfig(buyNowCart.id);\n\n return {\n createCheckoutSessionConfig,\n estimatedOrderAmount,\n productType:\n getShippableItemsCount(buyNowCart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface CheckoutConfig {\n payload: string;\n signature: string;\n public_key: string;\n}\n\nexport default class AmazonPayV2RequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createCheckoutConfig(cartId: string): Promise> {\n const body = { cartId };\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post('/api/storefront/payment/amazonpay', { headers, body });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2ButtonStrategy from './amazon-pay-v2-button-strategy';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\n\nconst createAmazonPayV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n const amazonPayV2RequestSender = new AmazonPayV2RequestSender(requestSender);\n const amazonPayV2PaymentProcessor = createAmazonPayV2PaymentProcessor();\n\n return new AmazonPayV2ButtonStrategy(\n paymentIntegrationService,\n amazonPayV2PaymentProcessor,\n amazonPayV2RequestSender,\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2ButtonStrategy, [{ id: 'amazonpay' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n AddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n Checkout,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport ApplePayButtonInitializeOptions, {\n WithApplePayButtonInitializeOptions,\n} from './apple-pay-button-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nexport enum ButtonStyleOption {\n Black = 'black',\n White = 'white',\n WhiteBorder = 'white-border',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nconst getApplePayButtonStyle = (option?: ButtonStyleOption): Record => {\n const defaultStyle: Record = {\n backgroundPosition: '50% 50%',\n backgroundRepeat: 'no-repeat',\n backgroundSize: '100% 60%',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: '32px',\n minWidth: '90px',\n padding: '1.5rem',\n display: 'block',\n };\n\n switch (option) {\n case ButtonStyleOption.White:\n defaultStyle.backgroundColor = '#fff';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-black)';\n break;\n\n case ButtonStyleOption.WhiteBorder:\n defaultStyle.backgroundColor = '#fff';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-black)';\n defaultStyle.border = '0.5px solid #000';\n break;\n\n case ButtonStyleOption.Black:\n default:\n defaultStyle.backgroundColor = '#000';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-white)';\n }\n\n return defaultStyle;\n};\n\nexport default class ApplePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _requiresShipping?: boolean;\n private _buyNowInitializeOptions?: ApplePayButtonInitializeOptions['buyNowInitializeOptions'];\n private _onAuthorizeCallback = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onPaymentAuthorize, buyNowInitializeOptions, requiresShipping } = applepay;\n\n this._requiresShipping = requiresShipping;\n\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n this._onAuthorizeCallback = onPaymentAuthorize;\n\n if (!buyNowInitializeOptions) {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const cart = state.getCart();\n\n if (cart) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\n\n if (this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n\n this._applePayButton = this._createButton(\n containerId,\n this._paymentMethod.initializationData?.styleOption,\n );\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createButton(containerId: string, styleOption?: ButtonStyleOption): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n const button = document.createElement('div');\n\n button.setAttribute('role', 'button');\n button.setAttribute('aria-label', 'Apple Pay button');\n Object.assign(button.style, getApplePayButtonStyle(styleOption));\n\n container.appendChild(button);\n\n return button;\n }\n\n private async _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this._buyNowInitializeOptions &&\n typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody === 'function'\n ) {\n const {\n countryCode,\n currencyCode,\n merchantCapabilities,\n supportedNetworks,\n storeName,\n } = this._paymentMethod.initializationData;\n\n const request = this._getRequestWithEmptyTotal(\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n );\n\n if (this._requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n }\n\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, storeName);\n\n applePaySession.begin();\n } else {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(\n applePaySession,\n this._paymentMethod,\n config.storeProfile.storeName,\n );\n\n applePaySession.begin();\n }\n }\n\n private _getRequestWithEmptyTotal(\n countryCode: string,\n currencyCode: string,\n supportedNetworks: string[],\n merchantCapabilities: ApplePayJS.ApplePayMerchantCapability[],\n ): ApplePayJS.ApplePayPaymentRequest {\n return {\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n total: { label: '', amount: '0', type: 'pending' },\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n };\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n storeName: string,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (error) {\n throw new Error('Merchant validation failed');\n }\n };\n\n if (this._buyNowInitializeOptions && !this._requiresShipping) {\n applePaySession.onpaymentmethodselected = async () => {\n await this._createBuyNowCart();\n this._handlePaymentMethodSelected(applePaySession);\n };\n }\n\n applePaySession.onshippingcontactselected = async (event) => {\n if (this._buyNowInitializeOptions && this._requiresShipping) {\n await this._createBuyNowCart();\n }\n\n await this._handleShippingContactSelected(applePaySession, storeName, event);\n };\n\n applePaySession.onshippingmethodselected = async (event) => {\n await this._handleShippingMethodSelected(applePaySession, storeName, event);\n };\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n throw new PaymentMethodCancelledError();\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _createBuyNowCart() {\n try {\n const cartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(buyNowCart.id);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private _handlePaymentMethodSelected(applePaySession: ApplePaySession) {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n\n delete request.total.type;\n\n applePaySession.completePaymentMethodSelection({\n newTotal: request.total,\n newLineItems: request.lineItems,\n });\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping address update failed');\n }\n\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n throw new Error('Shipping options update failed');\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping option selection update failed.');\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n throw new Error('Payment cannot complete');\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n const state = this._paymentIntegrationService.getState();\n const braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonStrategy from './apple-pay-button-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import { stringifyUrl } from 'query-string';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltButtonStyleOptions,\n BoltHostWindow,\n BoltPaymentMethod,\n StyleButtonShape,\n StyleButtonSize,\n} from './bolt';\nimport { WithBoltButtonInitializeOptions } from './bolt-button-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBoltButtonInitializeOptions,\n ): Promise {\n const { bolt, containerId, methodId } = options;\n const { buyNowInitializeOptions, style } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!bolt) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bolt\" argument is not provided.`,\n );\n }\n\n const isBuyNowFlow = Boolean(buyNowInitializeOptions);\n\n if (!isBuyNowFlow) {\n throw new NotImplementedError('Only buy now flow is implemented for Bolt button');\n }\n\n if (\n !buyNowInitializeOptions?.storefrontApiToken ||\n typeof buyNowInitializeOptions.storefrontApiToken !== 'string'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.storefrontApiToken\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: BoltPaymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n config.testMode,\n developerConfig,\n 'BigCommerce',\n buyNowInitializeOptions.storefrontApiToken,\n );\n\n this.renderButton(containerId, paymentMethod, style);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n if (typeof this.boltHostWindow.BoltConnect?.setupProductPageCheckout !== 'function') {\n return;\n }\n\n this.addButtonContainer(containerId, paymentMethod, style);\n this.boltHostWindow.BoltConnect.setupProductPageCheckout();\n }\n\n private addButtonContainer(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n const container = document.getElementById(containerId);\n\n if (!container) {\n return;\n }\n\n const boltButtonContainer = document.createElement('div');\n const boltButtonObject = document.createElement('object');\n\n boltButtonContainer.setAttribute('id', 'product-page-checkout-wrapper');\n boltButtonContainer.setAttribute('class', 'bolt-button-wrapper');\n boltButtonContainer.setAttribute('style', 'display:none');\n boltButtonContainer.setAttribute('data-tid', 'product-page-checkout-wrapper');\n\n boltButtonObject.setAttribute('data', this.getBoltObjectData(paymentMethod, style));\n boltButtonObject.setAttribute('class', 'bolt-product-checkout-button');\n\n boltButtonContainer.append(boltButtonObject);\n container.innerHTML = '';\n container.append(boltButtonContainer);\n }\n\n private getBoltObjectData(\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): string {\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n const domainUrl = this.boltScriptLoader.getDomainURL(!!config.testMode, developerConfig);\n const buttonHeight = this.getButtonHeight(style?.size);\n const buttonBorderRadius = this.getButtonBorderRadius(style?.shape, buttonHeight);\n\n return stringifyUrl({\n url: `https://${domainUrl}/v1/checkout_button`,\n query: {\n publishable_key: publishableKey,\n variant: 'ppc',\n height: buttonHeight,\n border_radius: buttonBorderRadius,\n },\n });\n }\n\n private getButtonHeight(buttonSize?: StyleButtonSize): number | undefined {\n if (!buttonSize) {\n return;\n }\n\n switch (buttonSize) {\n case StyleButtonSize.Small:\n return 25;\n\n case StyleButtonSize.Large:\n return 45;\n\n case StyleButtonSize.Medium:\n default:\n return 40;\n }\n }\n\n private getButtonBorderRadius(\n buttonShape?: StyleButtonShape,\n buttonHeight?: number,\n ): number | undefined {\n if (!buttonShape) {\n return;\n }\n\n switch (buttonShape) {\n case StyleButtonShape.Pill:\n return buttonHeight ? Math.round(buttonHeight / 2) : undefined;\n\n case StyleButtonShape.Rect:\n default:\n return 4;\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltButtonStrategy from './bolt-button-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltButtonStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltButtonStrategy, [{ id: 'bolt' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeDataCollector,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeVisaCheckoutButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const { clientToken, initializationData, config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const {\n currency: { code },\n cartAmount,\n } = state.getCartOrThrow();\n\n const visaCheckoutInstance = await this.braintreeSdk.getVisaCheckoutSdk(config.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n paymentRequest: {\n currencyCode: code,\n subtotal: String(cartAmount),\n },\n settings: {\n shipping: {\n collectShipping: true,\n },\n },\n });\n\n this.createSignInButton(containerId);\n\n await visaCheckoutInstance.init(initOptions);\n\n visaCheckoutInstance.on('payment.success', async (payment) => {\n await this.paymentSuccess(braintreeVisaCheckout, payment);\n });\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private async paymentSuccess(\n braintreeVisaCheckout: BraintreeVisaCheckout,\n payment: VisaCheckoutPaymentSuccessPayload,\n ) {\n return Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this.braintreeSdk.getDataCollectorOrThrow(),\n ]).then(([payload, deviceData]) => {\n const state = this.paymentIntegrationService.getState();\n\n const shipping = state.getShippingAddress();\n const billing = state.getBillingAddress();\n\n const {\n shippingAddress = this.toVisaCheckoutAddress(shipping),\n billingAddress = this.toVisaCheckoutAddress(billing),\n } = payload;\n\n return this.postForm(\n {\n ...payload,\n shippingAddress,\n billingAddress,\n },\n deviceData,\n );\n });\n }\n\n private postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: JSON.stringify({\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n }),\n billing_address: JSON.stringify(this.getAddress(userEmail, billingAddress)),\n shipping_address: JSON.stringify(this.getAddress(userEmail, shippingAddress)),\n });\n }\n\n private toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return this.insertVisaCheckoutButton(container);\n }\n\n private insertVisaCheckoutButton(container: Element): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.alignItems = 'flex-end';\n\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutButtonStrategy from './braintree-visa-checkout-button-strategy';\n\nconst createBraintreeVisaCheckoutButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreeVisaCheckoutButtonStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), hostWindow));\n\n return new BraintreeVisaCheckoutButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutButtonStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeTokenizationDetails } from './types';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeTokenizationDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeTokenizationDetails } from './types';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeTokenizationDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeSdk,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n mapToLegacyBillingAddress,\n mapToLegacyShippingAddress,\n PaypalButtonStyleColorOption,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n Cart,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n DefaultCheckoutButtonHeight,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isBraintreeError from '../is-braintree-error';\nimport { isUnsupportedBrowserError } from '../isUnsupportedBrowserError';\n\nimport { WithBraintreeVenmoInitializeOptions } from './braintree-venmo-initialize-options';\n\nconst getVenmoButtonStyle = (styles: PaypalStyleOptions): Record => {\n const { color, height } = styles;\n\n const colorParser = (c: string) => {\n if (c === PaypalButtonStyleColorOption.WHITE) {\n return '#FFFFFF';\n }\n\n return '#3D95CE';\n };\n\n return {\n backgroundColor: colorParser(color || ''),\n backgroundPosition: '50% 50%',\n backgroundSize: '80px auto',\n backgroundImage: `url(\"/app/assets/img/payment-providers/venmo-logo-${\n color === PaypalButtonStyleColorOption.WHITE\n ? PaypalButtonStyleColorOption.BLUE\n : PaypalButtonStyleColorOption.WHITE\n }.svg\")`,\n backgroundRepeat: 'no-repeat',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: `${height || DefaultCheckoutButtonHeight}px`,\n minWidth: '150px',\n height: '100%',\n width: '100%',\n border: color === PaypalButtonStyleColorOption.WHITE ? '1px solid black' : 'none',\n };\n};\n\nconst venmoButtonStyleHover = {\n backgroundColor: '#0a7fc2',\n};\n\ninterface BuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n}\n\nexport default class BraintreeVenmoButtonStrategy implements CheckoutButtonStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { braintreevenmo, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, initializationData }: PaymentMethod = paymentMethod;\n const { paymentButtonStyles } = initializationData;\n const { cartButtonStyles } = paymentButtonStyles || {};\n const styles = braintreevenmo?.style || cartButtonStyles;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n this.onError = braintreevenmo?.onError || this.handleError;\n this.braintreeSdk.initialize(clientToken);\n\n try {\n const braintreeVenmoCheckout = await this.braintreeSdk.getVenmoCheckoutOrThrow();\n\n this.renderVenmoButton(\n braintreeVenmoCheckout,\n containerId,\n braintreevenmo?.buyNowInitializeOptions,\n styles,\n );\n } catch (error) {\n if (isBraintreeError(error) || isUnsupportedBrowserError(error)) {\n this.handleInitializationVenmoError(error, containerId);\n }\n }\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n\n return Promise.resolve();\n }\n\n private handleError(error: BraintreeError) {\n throw new Error(error.message);\n }\n\n private async createBuyNowCart(\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions?.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const buyNowCart = await this.paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n return undefined;\n }\n\n private handleInitializationVenmoError(\n error: BraintreeError | UnsupportedBrowserError,\n containerId: string,\n ): void {\n this.removeVenmoContainer(containerId);\n\n return this.onError(error);\n }\n\n private removeVenmoContainer(containerId: string): void {\n const buttonContainer = document.getElementById(containerId);\n\n if (buttonContainer) {\n buttonContainer.remove();\n }\n }\n\n private renderVenmoButton(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n containerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n buttonStyles?: PaypalStyleOptions,\n ): void {\n const venmoButton = document.getElementById(containerId);\n const { color } = buttonStyles || {};\n\n if (!venmoButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n venmoButton.setAttribute('aria-label', 'Venmo');\n Object.assign(venmoButton.style, getVenmoButtonStyle(buttonStyles || {}));\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n venmoButton.addEventListener('click', async () => {\n venmoButton.setAttribute('disabled', 'true');\n\n const buyBowCart = await this.createBuyNowCart(buyNowInitializeOptions);\n\n if (braintreeVenmoCheckout.tokenize) {\n braintreeVenmoCheckout.tokenize(\n async (\n error: BraintreeError | undefined,\n payload: BraintreeTokenizePayload,\n ) => {\n venmoButton.removeAttribute('disabled');\n\n if (error) {\n this.onError(error);\n }\n\n await this.handlePostForm(payload, buyBowCart?.id);\n },\n );\n }\n });\n\n if (color === PaypalButtonStyleColorOption.BLUE) {\n venmoButton.addEventListener('mouseenter', () => {\n venmoButton.style.backgroundColor = venmoButtonStyleHover.backgroundColor;\n });\n\n venmoButton.addEventListener('mouseleave', () => {\n venmoButton.style.backgroundColor = getVenmoButtonStyle(\n buttonStyles || {},\n ).backgroundColor;\n });\n }\n }\n\n private async handlePostForm(\n payload: BraintreeTokenizePayload,\n buyNowCartId?: string,\n ): Promise {\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { nonce, details } = payload;\n\n this.formPoster.postForm('/checkout.php', {\n nonce,\n provider: 'braintreevenmo',\n payment_type: 'paypal',\n device_data: deviceData,\n action: 'set_external_checkout',\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n }\n}\n","import { UnsupportedBrowserError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport function isUnsupportedBrowserError(error: unknown): error is UnsupportedBrowserError {\n return error instanceof UnsupportedBrowserError;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVenmoButtonStrategy from './braintree-venmo-button-strategy';\n\nconst createBraintreeVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, braintreeHostWindow);\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeVenmoButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoButtonStrategy, [{ id: 'braintreevenmo' }]);\n","import {\n BuyNowCartCreationError,\n Cart,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithGooglePayButtonInitializeOptions } from './google-pay-button-initialize-option';\nimport GooglePayCustomerInitializeOptions from './google-pay-customer-initialize-options';\nimport { WithGooglePayPaymentInitializeOptions } from './google-pay-payment-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n GooglePayBuyNowInitializeOptions,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentButton?: HTMLElement;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _buyNowCart?: Cart;\n private _currencyCode?: string;\n private _buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions;\n private _countryCode?: string;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithGooglePayButtonInitializeOptions,\n ): Promise {\n if (!options.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n if (!options.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" is not a valid key.',\n );\n }\n\n const googlePayOptions = options[this._getMethodOrThrow()];\n\n if (!googlePayOptions) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n const { buyNowInitializeOptions, currencyCode, buttonColor, buttonType, onError } =\n googlePayOptions;\n\n let state = this._paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodOrThrow());\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(\n this._getMethodOrThrow(),\n );\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodOrThrow());\n }\n\n this._countryCode = paymentMethod.initializationData?.storeCountry;\n\n if (buyNowInitializeOptions) {\n if (!currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.currencyCode\" argument is not provided.`,\n );\n }\n\n this._currencyCode = currencyCode;\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(),\n !!buyNowInitializeOptions,\n currencyCode,\n );\n } else {\n await this._paymentIntegrationService.loadDefaultCheckout();\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(),\n );\n }\n\n this._paymentButton =\n this._paymentButton ??\n this._googlePayPaymentProcessor.addPaymentButton(options.containerId, {\n buttonColor: buttonColor ?? 'default',\n buttonType: buttonType ?? 'plain',\n onClick: this._handleClick(onError),\n });\n }\n\n deinitialize(): Promise {\n this._paymentButton?.remove();\n this._paymentButton = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n private _handleClick(\n onError: GooglePayCustomerInitializeOptions['onError'],\n ): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n try {\n if (this._buyNowInitializeOptions) {\n await this._createBuyNowCartOrThrow(this._buyNowInitializeOptions);\n } else {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n };\n }\n\n private async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n const shippingAddress =\n this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(response);\n const siteLink =\n window.location.pathname === '/embedded-checkout'\n ? this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink\n : undefined;\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress && !this._buyNowCart?.lineItems.digitalItems.length) {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutForm(\n this._getMethodOrThrow(),\n response,\n siteLink,\n );\n }\n\n private _getGooglePayClientOptions(): GooglePayPaymentOptions | undefined {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n }: IntermediatePaymentData): Promise => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n } = this._googlePayPaymentProcessor.getCallbackTriggers();\n\n if (!availableTriggers.includes(callbackTrigger)) {\n return;\n }\n\n const availableShippingOptions = addressChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleShippingAddressChange(\n shippingAddress,\n )\n : undefined;\n\n if (shippingOptionsChangeTriggers.includes(callbackTrigger)) {\n await this._googlePayPaymentProcessor.handleShippingOptionChange(\n shippingOptionData.id,\n );\n }\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(availableShippingOptions);\n }\n\n return this._getTransactionInfo(availableShippingOptions);\n },\n },\n };\n }\n\n private async _createBuyNowCartOrThrow(\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n try {\n this._buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(this._buyNowCart.id);\n } catch (error) {\n if (typeof error === 'string') {\n throw new BuyNowCartCreationError(error);\n }\n\n throw error;\n }\n }\n }\n\n private _getBuyNowTransactionInfo(availableShippingOptions?: ShippingOptionParameters) {\n if (!this._buyNowCart) {\n return;\n }\n\n const { cartAmount } = this._buyNowCart;\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode: this._getCurrencyCodeOrThrow(),\n totalPrice: totalPrice || String(cartAmount),\n totalPriceStatus: TotalPriceStatusType.FINAL,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n }\n\n private async _getTransactionInfo(availableShippingOptions?: ShippingOptionParameters) {\n await this._paymentIntegrationService.loadCheckout();\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n return {\n newTransactionInfo: {\n ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n }\n\n private _getMethodOrThrow(): keyof WithGooglePayButtonInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _getCurrencyCodeOrThrow(): string {\n return guard(\n this._currencyCode,\n () =>\n new InvalidArgumentError(\n 'Unable to initialize payment because \"options.currencyCode\" argument is not provided.',\n ),\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreeButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreeButtonStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayButtonStrategy from '../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(\n paymentIntegrationService,\n new PayPalCommerceScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceButtonStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2ButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV2ButtonStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3ButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV3ButtonStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeNetButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAuthorizeNetButtonStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComButtonStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourceButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayCybersourceButtonStrategy, [\n { id: 'googlepaycybersourcev2' },\n { id: 'googlepaybnz' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayOrbitalButtonStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayButtonStrategy from '../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayWorldpayAccessButtonStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartButtonStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceButtonInitializeOptions, {\n WithPayPalCommerceButtonInitializeOptions,\n} from './paypal-commerce-button-initialize-options';\n\nexport default class PayPalCommerceButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceButtonInitializeOptions,\n ): Promise {\n const { paypalcommerce, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(paypalcommerce?.buyNowInitializeOptions);\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !paypalcommerce.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof paypalcommerce.buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? paypalcommerce.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommerce: PayPalCommerceButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceButtonStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalMessagesSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditButtonInitializeOptions, {\n WithPayPalCommerceCreditButtonInitializeOptions,\n} from './paypal-commerce-credit-button-initialize-options';\n\nexport default class PayPalCommerceCreditButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const {\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n messagingContainerId,\n } = paypalcommercecredit || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n const state = this.paymentIntegrationService.getState();\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : state.getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\n\n const messagingContainer =\n messagingContainerId && document.getElementById(messagingContainerId);\n\n if (currencyCode && messagingContainer) {\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // TODO: update paypalBNPLConfiguration with empty array as default value when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const { paypalBNPLConfiguration } = paymentMethod.initializationData || {};\n let bannerConfiguration: PayPalBNPLConfigurationItem | undefined;\n\n if (paypalBNPLConfiguration) {\n bannerConfiguration = paypalBNPLConfiguration.find(({ id }) => id === 'cart');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n // TODO: remove this attributes reset when content service and PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n }\n\n const paypalSdk = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n currencyCode,\n );\n\n this.renderMessages(paypalSdk, messagingContainerId, bannerConfiguration);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercecredit: PayPalCommerceCreditButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n paypalcommercecredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private renderMessages(\n paypalMessagesSdk: PayPalMessagesSdk,\n messagingContainerId: string,\n bannerConfiguration?: PayPalBNPLConfigurationItem, // TODO: this should not be optional when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n const grandTotal = checkout.outstandingBalance;\n // TODO: default style can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const style = bannerConfiguration\n ? getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration)\n : {\n layout: 'text',\n };\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: grandTotal,\n placement: 'cart',\n style,\n };\n\n const paypalMessages = paypalMessagesSdk.Messages(paypalMessagesOptions);\n\n paypalMessages.render(`#${messagingContainerId}`);\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditButtonStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoButtonInitializeOptions, {\n WithPayPalCommerceVenmoButtonInitializeOptions,\n} from './paypal-commerce-venmo-button-initialize-options';\n\nexport default class PayPalCommerceVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceVenmoButtonInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n paypalcommercevenmo || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.getValidVenmoButtonStyles(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle = this.paypalCommerceIntegrationService.getValidButtonStyle(style);\n\n if (validButtonStyle.color === StyleButtonColor.gold) {\n return {\n ...validButtonStyle,\n color: undefined,\n };\n }\n\n return validButtonStyle;\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoButtonStrategy from './paypal-commerce-venmo-button-strategy';\n\nconst createPayPalCommerceVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoButtonStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsButtonOptions, {\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n} from './paypal-commerce-alternative-methods-button-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsButtonStrategy\n implements CheckoutButtonStrategy\n{\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n ): Promise {\n const { paypalcommercealternativemethods, containerId, methodId } = options;\n const {\n apm,\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n } = paypalcommercealternativemethods || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercealternativemethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n if (!apm) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.apm\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercealternativemethods);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercealternativemethods: PayPalCommerceAlternativeMethodsButtonOptions,\n ): void {\n const { apm, buyNowInitializeOptions, style, onEligibilityFailure } =\n paypalcommercealternativemethods;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(apm);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"options.paypalcommercealternativemethods.apm\" argument is not valid funding source.`,\n );\n }\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethod',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: apm,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsButtonStrategy from './paypal-commerce-alternative-methods-button-strategy';\n\nconst createPayPalCommerceAlternativeMethodsButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceAlternativeMethodsButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsButtonStrategy, [\n { id: 'paypalcommercealternativemethods' },\n]);\n","export interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressButtonInitializeOptions } from './paypal-express-button-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal-express-types';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalExpressScriptLoader: PaypalScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!options.paypal) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSDK = await this.paypalExpressScriptLoader.loadPaypalSDK(\n paymentMethod.config.merchantId,\n );\n\n this.renderButton(options, paypalSDK);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n paypalSDK: PaypalSDK,\n ) {\n const { containerId, methodId, paypal } = options;\n const { allowCredit, clientId, onPaymentError, shouldProcessPayment, style } = paypal;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: clientId };\n const fundingCreditOption = paypalSDK.FUNDING.CREDIT || 'credit';\n const allowedSources = allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !allowCredit ? [fundingCreditOption] : [];\n\n return paypalSDK.Button.render(\n {\n env,\n client: clientToken,\n commit: shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: this.getStyle(style),\n payment: (_, actions) => this.setupPayment(merchantId, actions, onPaymentError),\n onAuthorize: (data, actions) =>\n this.tokenizePayment(data, methodId, actions, shouldProcessPayment),\n },\n containerId,\n );\n }\n\n private getStyle(style?: Omit): PaypalStyleOptions {\n const { color, fundingicons, label, layout, shape, size, tagline } = style || {};\n\n return {\n color,\n fundingicons,\n label,\n layout,\n shape: shape || PaypalButtonStyleShapeOption.RECT,\n size: size === 'small' ? PaypalButtonStyleSizeOption.RESPONSIVE : size,\n tagline,\n };\n }\n\n private async setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n try {\n const state = await this.paymentIntegrationService.loadDefaultCheckout();\n const { id: cartId } = state.getCartOrThrow();\n const host = state.getHost() || '';\n\n const paymentRequest = await actions.request.post(\n `${host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n\n return paymentRequest.id;\n } catch (error) {\n if (onError && error instanceof StandardError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePayment(\n data: PaypalAuthorizeData,\n methodId: string,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const getPaymentData = await actions.payment.get(data.paymentID);\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: paymentMethod.id,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(getPaymentData.payer.payer_info),\n });\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalScriptLoader {\n private window: PaypalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async loadPaypalSDK(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n ...(merchantId && {\n attributes: { 'data-merchant-id': merchantId },\n }),\n };\n\n await this.scriptLoader.loadScript(scriptSrc, options);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalExpressButtonStrategy, PaypalExpressScriptLoader } from './index';\n\nconst createPaypalExpressButtonStrategy: CheckoutButtonStrategyFactory<\n PaypalExpressButtonStrategy\n> = (paymentIntegrationService) => {\n return new PaypalExpressButtonStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressButtonStrategy, [{ id: 'paypalexpress' }]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\n\nimport CheckoutButtonInitializer from './checkout-button-initializer';\nimport CheckoutButtonInitializerOptions from './checkout-button-initializer-options';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonRegistry from './create-checkout-button-registry';\nimport createCheckoutButtonRegistryV2 from './create-checkout-button-registry-v2';\n\n/**\n * Creates an instance of `CheckoutButtonInitializer`.\n *\n * @remarks\n * ```js\n * const initializer = createCheckoutButtonInitializer();\n *\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * braintreepaypal: {\n * container: '#checkoutButton',\n * },\n * });\n * ```\n *\n * @alpha\n * Please note that `CheckoutButtonInitializer` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutButtonInitializer`.\n */\nexport default function createCheckoutButtonInitializer(\n options?: CheckoutButtonInitializerOptions,\n): CheckoutButtonInitializer {\n const { host, locale = 'en' } = options ?? {};\n\n const config: ConfigState = {\n meta: {\n host: options?.host,\n locale: options?.locale,\n },\n errors: {},\n statuses: {},\n };\n\n const store = createCheckoutStore({ config });\n const requestSender = createRequestSender({ host });\n const formPoster = createFormPoster({ host });\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createCheckoutButtonRegistryV2(paymentIntegrationService);\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, locale, host),\n registryV2,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n ),\n );\n}\n","import {\n CheckoutButtonStrategy,\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories = defaultCheckoutButtonStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry<\n CheckoutButtonStrategy,\n CheckoutButtonStrategyResolveId\n >();\n\n for (const [, createCheckoutButtonStrategy] of Object.entries(\n checkoutButtonStrategyFactories,\n )) {\n if (\n !isResolvableModule<\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId\n >(createCheckoutButtonStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCheckoutButtonStrategy.resolveIds) {\n registry.register(resolverId, () =>\n createCheckoutButtonStrategy(paymentIntegrationService),\n );\n }\n }\n\n return registry;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { BraintreeSDKCreator } from '../payment/strategies/braintree';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport {\n BraintreePaypalButtonStrategy,\n BraintreePaypalCreditButtonStrategy,\n} from './strategies/braintree';\nimport { MasterpassButtonStrategy } from './strategies/masterpass';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\n locale: string,\n host?: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const braintreeSdkCreator = new BraintreeSDKCreator(\n new BraintreeScriptLoader(scriptLoader, window),\n );\n const cartRequestSender = new CartRequestSender(requestSender);\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalCreditButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.MASTERPASS,\n () =>\n new MasterpassButtonStrategy(\n store,\n checkoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.PAYPALEXPRESS,\n () =>\n new PaypalButtonStrategy(\n store,\n checkoutActionCreator,\n new PaypalScriptLoader(scriptLoader),\n formPoster,\n host,\n ),\n );\n\n return registry;\n}\n","import EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedContentOptions } from './iframe-content';\n\nexport enum EmbeddedCheckoutEventType {\n CheckoutComplete = 'CHECKOUT_COMPLETE',\n CheckoutError = 'CHECKOUT_ERROR',\n CheckoutLoaded = 'CHECKOUT_LOADED',\n FrameError = 'FRAME_ERROR',\n FrameLoaded = 'FRAME_LOADED',\n SignedOut = 'SIGNED_OUT',\n}\n\nexport interface EmbeddedCheckoutEventMap {\n [EmbeddedCheckoutEventType.CheckoutComplete]: EmbeddedCheckoutCompleteEvent;\n [EmbeddedCheckoutEventType.CheckoutError]: EmbeddedCheckoutErrorEvent;\n [EmbeddedCheckoutEventType.CheckoutLoaded]: EmbeddedCheckoutLoadedEvent;\n [EmbeddedCheckoutEventType.FrameError]: EmbeddedCheckoutFrameErrorEvent;\n [EmbeddedCheckoutEventType.FrameLoaded]: EmbeddedCheckoutFrameLoadedEvent;\n [EmbeddedCheckoutEventType.SignedOut]: EmbeddedCheckoutSignedOutEvent;\n}\n\nexport type EmbeddedCheckoutEvent =\n | EmbeddedCheckoutCompleteEvent\n | EmbeddedCheckoutErrorEvent\n | EmbeddedCheckoutFrameErrorEvent\n | EmbeddedCheckoutFrameLoadedEvent\n | EmbeddedCheckoutLoadedEvent\n | EmbeddedCheckoutSignedOutEvent;\n\nexport interface EmbeddedCheckoutCompleteEvent {\n type: EmbeddedCheckoutEventType.CheckoutComplete;\n}\n\nexport interface EmbeddedCheckoutErrorEvent {\n type: EmbeddedCheckoutEventType.CheckoutError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutLoadedEvent {\n type: EmbeddedCheckoutEventType.CheckoutLoaded;\n}\n\nexport interface EmbeddedCheckoutFrameErrorEvent {\n type: EmbeddedCheckoutEventType.FrameError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutFrameLoadedEvent {\n type: EmbeddedCheckoutEventType.FrameLoaded;\n payload?: EmbeddedContentOptions;\n}\n\nexport interface EmbeddedCheckoutSignedOutEvent {\n type: EmbeddedCheckoutEventType.SignedOut;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error we are not able to sign in a shopper because the provided\n * login token is invalid.\n */\nexport default class InvalidLoginTokenError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'InvalidLoginTokenError';\n this.type = 'invalid_login_token';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport enum NotEmbeddableErrorType {\n MissingContainer = 'missing_container',\n MissingContent = 'missing_content',\n UnknownError = 'unknown_error',\n}\n\n/**\n * Throw this error if we are not able to embed the checkout form as an iframe.\n * This can be due to the fact that the provided container ID is invalid, or the\n * checkout form fails to load inside the iframe. It can also be due to an\n * unknown reason.\n */\nexport default class NotEmbeddableError extends StandardError {\n constructor(\n message?: string,\n public subtype: NotEmbeddableErrorType = NotEmbeddableErrorType.UnknownError,\n ) {\n super(message || 'Unable to embed the checkout form.');\n\n this.name = 'NotEmbeddableError';\n this.type = 'not_embeddable';\n }\n}\n","import EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nexport enum EmbeddedContentEventType {\n StyleConfigured = 'STYLE_CONFIGURED',\n}\n\nexport interface EmbeddedContentEventMap {\n [EmbeddedContentEventType.StyleConfigured]: EmbeddedContentStyleConfiguredEvent;\n}\n\nexport type EmbeddedContentEvent = EmbeddedContentStyleConfiguredEvent;\n\nexport interface EmbeddedContentStyleConfiguredEvent {\n type: EmbeddedContentEventType.StyleConfigured;\n payload: EmbeddedCheckoutStyles;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { IFrameComponent, IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { InvalidLoginTokenError, NotEmbeddableError, NotEmbeddableErrorType } from './errors';\nimport { EmbeddedContentEvent, EmbeddedContentEventType } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport const ALLOW_COOKIE_ATTEMPT_INTERVAL = 10 * 60 * 1000;\nexport const IS_COOKIE_ALLOWED_KEY = 'isCookieAllowed';\nexport const LAST_ALLOW_COOKIE_ATTEMPT_KEY = 'lastAllowCookieAttempt';\n\n@bind\nexport default class EmbeddedCheckout {\n private _iframe?: IFrameComponent;\n private _isAttached: boolean;\n\n /**\n * @internal\n */\n constructor(\n private _iframeCreator: ResizableIframeCreator,\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _loadingIndicator: LoadingIndicator,\n private _requestSender: RequestSender,\n private _storage: BrowserStorage,\n private _location: Location,\n private _options: EmbeddedCheckoutOptions,\n ) {\n this._isAttached = false;\n\n if (this._options.onComplete) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutComplete,\n this._options.onComplete,\n );\n }\n\n if (this._options.onError) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutError,\n this._options.onError,\n );\n }\n\n if (this._options.onLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutLoaded,\n this._options.onLoad,\n );\n }\n\n if (this._options.onFrameLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.FrameLoaded,\n this._options.onFrameLoad,\n );\n }\n\n if (this._options.onSignOut) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.SignedOut,\n this._options.onSignOut,\n );\n }\n\n this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, () =>\n this._configureStyles(),\n );\n }\n\n attach(): Promise {\n if (this._isAttached) {\n return Promise.resolve(this);\n }\n\n this._isAttached = true;\n this._messageListener.listen();\n this._loadingIndicator.show(this._options.containerId);\n\n return this._allowCookie()\n .then(() => this._attemptLogin())\n .then((url) => this._iframeCreator.createFrame(url, this._options.containerId))\n .then((iframe) => {\n this._iframe = iframe;\n\n this._configureStyles();\n this._loadingIndicator.hide();\n })\n .catch((error) => {\n this._isAttached = false;\n\n return this._retryAllowCookie(error).catch(() => {\n this._messageListener.trigger({\n type: EmbeddedCheckoutEventType.FrameError,\n payload: error,\n });\n\n this._loadingIndicator.hide();\n\n throw error;\n });\n })\n .then(() => this);\n }\n\n detach(): void {\n if (!this._isAttached) {\n return;\n }\n\n this._isAttached = false;\n this._messageListener.stopListen();\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe.iFrameResizer.close();\n }\n }\n\n private _configureStyles(): void {\n if (!this._iframe || !this._iframe.contentWindow || !this._options.styles) {\n return;\n }\n\n this._messagePoster.setTarget(this._iframe.contentWindow);\n\n this._messagePoster.post({\n type: EmbeddedContentEventType.StyleConfigured,\n payload: this._options.styles,\n });\n }\n\n private _attemptLogin(): Promise {\n if (!/^\\/login\\/token/.test(parseUrl(this._options.url).pathname)) {\n return Promise.resolve(this._options.url);\n }\n\n return this._requestSender\n .post<{ redirectUrl: string }>(this._options.url)\n .then(({ body: { redirectUrl } }) => redirectUrl)\n .catch((response) => Promise.reject(new InvalidLoginTokenError(response)));\n }\n\n /**\n * This workaround is required for certain browsers (namely Safari) that\n * prevent session cookies to be set for a third party website unless the\n * user has recently visited such website. Therefore, before we attempt to\n * login or set an active cart in the session, we need to first redirect the\n * user to the domain of Embedded Checkout.\n */\n private _allowCookie(): Promise {\n if (this._storage.getItem(IS_COOKIE_ALLOWED_KEY)) {\n return Promise.resolve();\n }\n\n this._storage.setItem(IS_COOKIE_ALLOWED_KEY, true);\n\n // It could be possible that the flag is set to true but the browser has\n // already removed the permission to store third-party cookies. In that\n // case, we should try to redirect the user again. But we only want to\n // do it once within a fixed interval. This is to avoid getting into a\n // redirect loop if the shopper actually doesn't have a valid card\n // session.\n this._storage.setItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY, Date.now());\n\n const { origin } = parseUrl(this._options.url);\n const redirectUrl = `${origin}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(\n this._location.href,\n )}`;\n\n document.body.style.visibility = 'hidden';\n this._location.replace(redirectUrl);\n\n return new Promise(() => {});\n }\n\n private _retryAllowCookie(error: EmbeddedCheckoutError): Promise {\n const lastAttempt = Number(this._storage.getItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY));\n const canRetry =\n (!lastAttempt || Date.now() - lastAttempt > ALLOW_COOKIE_ATTEMPT_INTERVAL) &&\n error instanceof NotEmbeddableError &&\n error.subtype === NotEmbeddableErrorType.MissingContent;\n\n if (!canRetry) {\n return Promise.reject();\n }\n\n this._storage.removeItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY);\n this._storage.removeItem(IS_COOKIE_ALLOWED_KEY);\n\n return this._allowCookie();\n }\n}\n","import { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { appendWww, parseUrl } from '../common/url';\n\nimport { EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport { NotEmbeddableError, NotEmbeddableErrorType } from './errors';\n\nexport interface ExtendedHTMLIFrameElement extends HTMLIFrameElement {\n allowPaymentRequest?: boolean;\n}\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(src: string, containerId: string): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new NotEmbeddableError(\n 'Unable to embed the iframe because the container element could not be found.',\n NotEmbeddableErrorType.MissingContainer,\n );\n }\n\n const iframe: ExtendedHTMLIFrameElement = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n iframe.allowPaymentRequest = true;\n iframe.allow = 'payment';\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout).catch((error) => {\n container.removeChild(iframe);\n\n throw error;\n });\n }\n\n private _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n ): Promise {\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n reject(\n new NotEmbeddableError(\n 'Unable to embed the iframe because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (\n event.origin !== parseUrl(iframe.src).origin &&\n event.origin !== appendWww(parseUrl(iframe.src)).origin\n ) {\n return;\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameError)) {\n teardown();\n reject(\n new NotEmbeddableError(\n event.data.payload.message,\n NotEmbeddableErrorType.MissingContent,\n ),\n );\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameLoaded)) {\n iframe.style.display = '';\n\n const contentId = event.data.payload && event.data.payload.contentId;\n const iframes = iframeResizer(\n {\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: contentId ? 'taggedElement' : 'lowestElement',\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckout from './embedded-checkout';\nimport { EmbeddedCheckoutEventMap } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { EmbeddedContentEvent } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nconst STORAGE_PREFIX = 'BigCommerce.EmbeddedCheckout';\n\n/**\n * Embed the checkout form in an iframe.\n *\n * @remarks\n * Once the iframe is embedded, it will automatically resize according to the\n * size of the checkout form. It will also notify the parent window when certain\n * events have occurred. i.e.: when the form is loaded and ready to be used.\n *\n * ```js\n * embedCheckout({\n * url: 'https://checkout/url',\n * containerId: 'container-id',\n * });\n * ```\n *\n * @param options - Options for embedding the checkout form.\n * @returns A promise that resolves to an instance of `EmbeddedCheckout`.\n */\nexport default function embedCheckout(options: EmbeddedCheckoutOptions): Promise {\n const origin = parseUrl(options.url).origin;\n const embeddedCheckout = new EmbeddedCheckout(\n new ResizableIframeCreator(),\n new IframeEventListener(origin),\n new IframeEventPoster(origin),\n new LoadingIndicator({ styles: options.styles && options.styles.loadingIndicator }),\n createRequestSender(),\n new BrowserStorage(STORAGE_PREFIX),\n window.location,\n options,\n );\n\n return embeddedCheckout.attach();\n}\n","import { EmbeddedCheckoutFrameLoadedEvent } from '../embedded-checkout-events';\n\nexport default function handleFrameLoadedEvent(message: EmbeddedCheckoutFrameLoadedEvent): void {\n if (!message.payload || !message.payload.contentId) {\n return;\n }\n\n const body = document.getElementById(message.payload.contentId);\n\n if (!body || body.hasAttribute('data-iframe-height')) {\n return;\n }\n\n body.setAttribute('data-iframe-height', '');\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: unknown): error is CustomError {\n return typeof error === 'object' && error !== null && 'message' in error && 'type' in error;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CustomError, isCustomError } from '../../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport EmbeddedCheckoutError from '../embedded-checkout-error';\nimport {\n EmbeddedCheckoutCompleteEvent,\n EmbeddedCheckoutErrorEvent,\n EmbeddedCheckoutEvent,\n EmbeddedCheckoutEventMap,\n EmbeddedCheckoutEventType,\n EmbeddedCheckoutFrameErrorEvent,\n EmbeddedCheckoutFrameLoadedEvent,\n EmbeddedCheckoutLoadedEvent,\n EmbeddedCheckoutSignedOutEvent,\n} from '../embedded-checkout-events';\nimport EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport { EmbeddedContentEventMap, EmbeddedContentEventType } from './embedded-content-events';\nimport EmbeddedContentOptions from './embedded-content-options';\n\n@bind\nexport default class IframeEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n /**\n * @internal\n */\n constructor(\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _untargetedMessagePoster: IframeEventPoster,\n private _messageHandlers: EventCallbacks = {},\n ) {\n this._messageListener.listen();\n }\n\n postComplete(): void {\n const message: EmbeddedCheckoutCompleteEvent = {\n type: EmbeddedCheckoutEventType.CheckoutComplete,\n };\n\n this._postMessage(message);\n }\n\n postError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutErrorEvent = {\n type: EmbeddedCheckoutEventType.CheckoutError,\n payload: this._transformError(payload),\n };\n\n this._postMessage(message);\n }\n\n postFrameError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutFrameErrorEvent = {\n type: EmbeddedCheckoutEventType.FrameError,\n payload: this._transformError(payload),\n };\n\n // Ideally, all messages should be targeted at a specific origin.\n // However, for `FrameError` message, we have to post it in an\n // untargeted fashion. This is because the error could be caused by a\n // missing cart. That makes it not possible to determine of site origin\n // of the parent window. Nevertheless, we still want to notify the\n // parent window about the error.\n this._postMessage(message, { untargeted: true });\n }\n\n postFrameLoaded(payload?: EmbeddedContentOptions): void {\n const message: EmbeddedCheckoutFrameLoadedEvent = {\n type: EmbeddedCheckoutEventType.FrameLoaded,\n payload,\n };\n\n this._postMessage(message);\n }\n\n postLoaded(): void {\n const message: EmbeddedCheckoutLoadedEvent = {\n type: EmbeddedCheckoutEventType.CheckoutLoaded,\n };\n\n this._postMessage(message);\n }\n\n postSignedOut(): void {\n const message: EmbeddedCheckoutSignedOutEvent = {\n type: EmbeddedCheckoutEventType.SignedOut,\n };\n\n this._postMessage(message);\n }\n\n receiveStyles(handler: (styles: EmbeddedCheckoutStyles) => void): void {\n this._messageListener.addListener(\n EmbeddedContentEventType.StyleConfigured,\n ({ payload }) => {\n handler(payload);\n },\n );\n }\n\n private _postMessage(message: EmbeddedCheckoutEvent, options?: { untargeted?: boolean }): void {\n this._notifyMessageHandlers(message);\n\n if (options && options.untargeted) {\n return this._untargetedMessagePoster.post(message);\n }\n\n this._messagePoster.post(message);\n }\n\n private _notifyMessageHandlers(message: EmbeddedCheckoutEvent): void {\n Object.keys(this._messageHandlers).forEach((key) => {\n if (message.type !== key) {\n return;\n }\n\n const handler = this._messageHandlers[key];\n\n if (handler) {\n (handler as (event: EmbeddedCheckoutEvent) => void).call(null, message);\n }\n });\n }\n\n private _transformError(error: Error | CustomError): EmbeddedCheckoutError {\n return {\n message: error.message,\n type: isCustomError(error) ? error.type : undefined,\n subtype: isCustomError(error) ? error.subtype : undefined,\n };\n }\n}\n\nexport type EventCallbacks = {\n [key in keyof TEventMap]?: (event: TEventMap[key]) => void;\n};\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\n\n@bind\nexport default class NoopEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n postComplete(): void {}\n\n postError(): void {}\n\n postFrameError(): void {}\n\n postFrameLoaded(): void {}\n\n postLoaded(): void {}\n\n postSignedOut(): void {}\n\n receiveStyles(): void {}\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../../common/iframe';\nimport { EmbeddedCheckoutEvent, EmbeddedCheckoutEventType } from '../embedded-checkout-events';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport EmbeddedCheckoutMessengerOptions from './embedded-checkout-messenger-options';\nimport { EmbeddedContentEventMap } from './embedded-content-events';\nimport handleFrameLoadedEvent from './handle-frame-loaded-event';\nimport IframeEmbeddedCheckoutMessenger from './iframe-embedded-checkout-messenger';\nimport NoopEmbeddedCheckoutMessenger from './noop-embedded-checkout-messenger';\n\n/**\n * Create an instance of `EmbeddedCheckoutMessenger`.\n *\n * @remarks\n * The object is responsible for posting messages to the parent window from the\n * iframe when certain events have occurred. For example, when the checkout\n * form is first loaded, you should notify the parent window about it.\n *\n * The iframe can only be embedded in domains that are allowed by the store.\n *\n * ```ts\n * const messenger = createEmbeddedCheckoutMessenger({\n * parentOrigin: 'https://some/website',\n * });\n *\n * messenger.postFrameLoaded();\n * ```\n *\n * @alpha\n * Please note that this feature is currently in an early stage of development.\n * Therefore the API is unstable and not ready for public consumption.\n *\n * @param options - Options for creating `EmbeddedCheckoutMessenger`\n * @returns - An instance of `EmbeddedCheckoutMessenger`\n */\nexport default function createEmbeddedCheckoutMessenger(\n options: EmbeddedCheckoutMessengerOptions,\n): EmbeddedCheckoutMessenger {\n setupContentWindowForIframeResizer();\n\n const parentWindow = options.parentWindow || window.parent;\n\n // Return a No-op messenger if it is not called inside an iframe\n if (window === parentWindow) {\n return new NoopEmbeddedCheckoutMessenger();\n }\n\n return new IframeEmbeddedCheckoutMessenger(\n new IframeEventListener(options.parentOrigin),\n new IframeEventPoster(options.parentOrigin, parentWindow),\n new IframeEventPoster('*', parentWindow),\n { [EmbeddedCheckoutEventType.FrameLoaded]: handleFrameLoadedEvent },\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"intl-messageformat\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"messageformat\");","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\nimport MessageFormat from 'messageformat';\n\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { Logger } from '../common/log';\n\nimport LanguageConfig, {\n Locales,\n TransformedLanguageConfig,\n TransformedTranslations,\n Translations,\n} from './language-config';\n\nconst DEFAULT_LOCALE = 'en';\nconst KEY_PREFIX = 'optimized_checkout';\n\n/**\n * Responsible for getting language strings.\n *\n * This object can be used to retrieve language strings that are most\n * appropriate for a given locale.\n *\n * The language strings provided to the object should follow [ICU\n * MessageFormat](http://userguide.icu-project.org/formatparse/messages) syntax.\n */\n@bind\nexport default class LanguageService {\n private _locale: string;\n private _locales: Locales;\n private _translations: TransformedTranslations;\n private _formatters: { [key: string]: any };\n private _isCspNonceExperimentEnabled: boolean;\n\n /**\n * @internal\n */\n constructor(config: Partial, private _logger: Logger) {\n const { locale, locales, translations } = this._transformConfig(config);\n\n this._locale = locale;\n this._locales = locales;\n this._translations = translations;\n this._formatters = {};\n this._isCspNonceExperimentEnabled = config.isCspNonceExperimentEnabled ?? true;\n }\n\n /**\n * Remaps a set of language strings with a different set of keys.\n *\n * ```js\n * service.mapKeys({\n * 'new_key': 'existing_key',\n * });\n *\n * console.log(service.translate('new_key'));\n * ```\n *\n * @param maps - The set of language strings.\n */\n mapKeys(maps: { [key: string]: string }): void {\n Object.keys(maps).forEach((key) => {\n const translationKey = `${KEY_PREFIX}.${maps[key]}`;\n\n this._translations[`${KEY_PREFIX}.${key}`] = this._translations[translationKey];\n });\n }\n\n /**\n * Gets the preferred locale of the current customer.\n *\n * @returns The preferred locale code.\n */\n getLocale(): string {\n return this._hasTranslations() ? this._locale : DEFAULT_LOCALE;\n }\n\n /**\n * Gets a language string by a key.\n *\n * ```js\n * service.translate('language_key');\n * ```\n *\n * If the language string contains a placeholder, you can replace it by\n * providing a second argument.\n *\n * ```js\n * service.translate('language_key', { placeholder: 'Hello' });\n * ```\n *\n * @param key - The language key.\n * @param data - Data for replacing placeholders in the language string.\n * @returns The translated language string.\n */\n translate(key: string, data: TranslationData = {}): string {\n const prefixedKey = `${KEY_PREFIX}.${key}`;\n\n if (typeof this._translations[prefixedKey] !== 'string') {\n this._logger.warn(`Translation key \"${prefixedKey}\" is missing`);\n\n return prefixedKey;\n }\n\n if (this._isCspNonceExperimentEnabled) {\n if (!this._formatters[prefixedKey]) {\n this._formatters[prefixedKey] = new IntlMessageFormat(\n this._escapeSpecialCharacters(this._translations[prefixedKey] || ''),\n this._locales[prefixedKey],\n undefined,\n { ignoreTag: true },\n );\n }\n\n try {\n return this._formatters[prefixedKey].format(this._transformData(data));\n } catch (error) {\n if (this._isFormatError(error)) {\n return error.originalMessage ?? '';\n }\n\n throw error;\n }\n }\n\n if (!this._formatters[prefixedKey]) {\n const messageFormat = new MessageFormat(this._locales[prefixedKey]);\n\n this._formatters[prefixedKey] = messageFormat.compile(\n this._translations[prefixedKey] || '',\n );\n }\n\n return this._formatters[prefixedKey](this._transformData(data));\n }\n\n private _transformConfig(config: Partial = {}): TransformedLanguageConfig {\n const output: TransformedLanguageConfig = {\n defaultLocale: '',\n defaultTranslations: {},\n translations: {},\n locales: {},\n locale: config.locale || DEFAULT_LOCALE,\n };\n\n const locales = config.locales || {};\n const translations = this._flattenObject(config.translations || {});\n const defaultTranslations = this._flattenObject(config.defaultTranslations || {});\n const fallbackTranslations = this._flattenObject(config.fallbackTranslations || {});\n const translationKeys = union(\n Object.keys(fallbackTranslations),\n Object.keys(defaultTranslations),\n Object.keys(translations),\n );\n\n translationKeys.forEach((key) => {\n if (translations && translations[key]) {\n output.translations[key] = translations[key];\n output.locales[key] = locales[key] || output.locale;\n } else if (defaultTranslations[key]) {\n output.translations[key] = defaultTranslations[key];\n output.locales[key] = config.defaultLocale ?? DEFAULT_LOCALE;\n } else {\n output.translations[key] = fallbackTranslations[key];\n output.locales[key] = config.fallbackLocale ?? DEFAULT_LOCALE;\n }\n });\n\n return output;\n }\n\n private _flattenObject(\n object: Translations,\n result: TransformedTranslations = {},\n parentKey = '',\n ): TransformedTranslations {\n try {\n Object.keys(object).forEach((key) => {\n const value = object[key];\n const resultKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (isObject(value)) {\n return this._flattenObject(value, result, resultKey);\n }\n\n result[resultKey] = value;\n });\n } catch (err) {\n this._logger.warn(`Unable to parse object: ${err}`);\n }\n\n return result;\n }\n\n private _transformData(data: TranslationData): TranslationData {\n return Object.keys(data).reduce((result, key) => {\n const value = data[key];\n\n result[key] = value === null || value === undefined ? '' : value;\n\n return result;\n }, {} as TranslationData);\n }\n\n private _hasTranslations(): boolean {\n return (\n Object.keys(this._locales)\n .map((key) => this._locales[key])\n .filter((code) => code.split('-')[0] === this._locale.split('-')[0]).length > 0\n );\n }\n\n private _isFormatError(error: unknown): error is FormatError {\n return typeof error === 'object' && error !== null && 'originalMessage' in error;\n }\n\n private _escapeSpecialCharacters(message: string) {\n return message.replace(/(\\w+)='([^']*)'/g, \"$1=''$2''\");\n }\n}\n\nexport interface TranslationData {\n [key: string]: string | number;\n}\n","import { getDefaultLogger } from '../common/log';\n\nimport LanguageConfig from './language-config';\nimport LanguageService from './language-service';\n\n/**\n * Creates an instance of `LanguageService`.\n *\n * @remarks\n * ```js\n * const language = {{{langJson 'optimized_checkout'}}}; // `langJson` is a Handlebars helper provided by BigCommerce's Stencil template engine.\n * const service = createLanguageService(language);\n *\n * console.log(service.translate('address.city_label'));\n * ```\n *\n * @param config - A configuration object.\n * @returns An instance of `LanguageService`.\n */\nexport default function createLanguageService(\n config: Partial = {},\n): LanguageService {\n return new LanguageService(config, getDefaultLogger());\n}\n","import { CurrencyFormatter } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { StoreConfig } from '../config';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * @param config - The config object containing the currency configuration\n * @returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import {\n AnalyticsTrackerWindow,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\ninterface AnalyticsTrackerWindowGA extends AnalyticsTrackerWindow {\n ga(command: string, eventName: string, payload: AnalyticPayload): void;\n}\n\nfunction isAnalyticsTrackerWindowGA(\n window: Window | AnalyticsTrackerWindowGA,\n): window is AnalyticsTrackerWindowGA {\n return window && 'ga' in window && typeof window.ga === 'function';\n}\n\nexport function isGoogleAnalyticsAvailable(): boolean {\n return isAnalyticsTrackerWindow(window) && isAnalyticsTrackerWindowGA(window);\n}\n\nexport function sendGoogleAnalytics(type: string, payload: AnalyticPayload): void {\n if (isAnalyticsTrackerWindowGA(window)) {\n window.ga('send', type, {\n ...payload,\n nonInteraction: false,\n });\n }\n}\n\n/**\n * Max size of the payload for the Google Analytics module\n * if the limit will be succeeded, the GA throwing a silent error,\n * and only in debug mode you can see it\n */\nexport function isPayloadSizeLimitReached(obj: AnalyticPayload): boolean {\n const ANALYTICS_MAX_URI_LENGTH = 8096;\n\n return serializeAnalyticsEventPayload(obj).length >= ANALYTICS_MAX_URI_LENGTH;\n}\n\nfunction serializeAnalyticsEventPayload(obj: AnalyticPayload): string {\n return Object.keys(obj)\n .reduce((acc: string[], key) => {\n const type = typeof obj[key];\n\n if (type === 'string' || type === 'number') {\n return [...acc, `${key}=${obj[key]}`];\n }\n\n if (type === 'object' && obj[key] !== null) {\n return [...acc, serializeAnalyticsEventPayload(obj[key] as AnalyticPayload)];\n }\n\n return acc;\n }, [])\n .join('&');\n}\n\ninterface AnalyticPayload {\n [key: string]: unknown;\n}\n","import { keys } from 'lodash';\n\nimport {\n AnalyticsExtraItemsManager,\n AnalyticsTracker,\n ExtraItemsData,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { DigitalItem, LineItemMap, PhysicalItem } from '../cart';\nimport { Checkout, CheckoutService } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { ShopperCurrency, StoreProfile } from '../config';\nimport { Coupon } from '../coupon';\nimport { Order } from '../order';\nimport { ShippingOption } from '../shipping';\n\nimport {\n isGoogleAnalyticsAvailable,\n isPayloadSizeLimitReached,\n sendGoogleAnalytics,\n} from './analytics-tracker-ga';\nimport StepTracker from './step-tracker';\n\nexport interface StepTrackerConfig {\n checkoutSteps?: AnalyticStepType[];\n}\n\nexport type AnalyticStepType = 'customer' | 'shipping' | 'billing' | 'payment';\n\nexport enum AnalyticStepId {\n CUSTOMER = 1,\n SHIPPING,\n BILLING,\n PAYMENT,\n}\n\nconst ANALYTIC_STEPS: { [key: string]: AnalyticStepId } = {\n customer: AnalyticStepId.CUSTOMER,\n shipping: AnalyticStepId.SHIPPING,\n billing: AnalyticStepId.BILLING,\n payment: AnalyticStepId.PAYMENT,\n};\n\nexport default class AnalyticsStepTracker implements StepTracker {\n private _checkoutStarted = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private _viewedSteps: { [key in AnalyticStepId]?: boolean } = {};\n private _analyticStepOrder: AnalyticStepType[] = ['customer', 'shipping', 'billing', 'payment'];\n\n constructor(\n private checkoutService: CheckoutService,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n private analytics: AnalyticsTracker,\n { checkoutSteps }: StepTrackerConfig = {},\n ) {\n if (checkoutSteps !== undefined) {\n if (checkoutSteps.some((value) => !(value in ANALYTIC_STEPS))) {\n throw new InvalidArgumentError(\n `Invalid checkout steps provided. Valid values are: ${keys(ANALYTIC_STEPS).join(\n ', ',\n )}.`,\n );\n }\n\n this._analyticStepOrder = checkoutSteps;\n }\n }\n\n trackCheckoutStarted(): void {\n if (this._checkoutStarted) {\n return;\n }\n\n const checkout = this.getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const {\n coupons,\n grandTotal,\n shippingCostTotal,\n taxTotal,\n cart: { lineItems, discountAmount, id },\n } = checkout;\n\n const extraItemsData = this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n\n this.analytics.track(\n 'Checkout Started',\n this.getTrackingPayload({\n revenue: grandTotal,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n lineItems,\n extraItemsData,\n }),\n );\n\n this._checkoutStarted = true;\n }\n\n trackOrderComplete(): void {\n const order = this.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n taxTotal,\n discountAmount,\n coupons,\n lineItems,\n cartId,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n const extraItemsData = this.analyticsExtraItemsManager.readExtraItemsData(cartId);\n\n if (extraItemsData === null) {\n return;\n }\n\n const isMissingOrdersExperimentEnabled = this.checkoutService.getState().data.getConfig()\n ?.checkoutSettings.features['DATA-6891.missing_orders_within_GA'];\n\n const payload = this.getTrackingPayload({\n orderId,\n revenue: orderAmount,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n extraItemsData,\n lineItems,\n });\n\n if (\n isMissingOrdersExperimentEnabled &&\n isGoogleAnalyticsAvailable() &&\n isPayloadSizeLimitReached(payload)\n ) {\n sendGoogleAnalytics('transaction', {\n '&ti': payload.order_id,\n '&ta': payload.affiliation,\n '&tr': payload.revenue,\n '&ts': payload.shipping,\n '&tt': payload.tax,\n '&tcc': payload.coupon,\n '&cu': payload.currency,\n });\n payload.products.forEach((product) => {\n sendGoogleAnalytics('item', {\n '&ti': payload.order_id,\n '&in': product.name,\n '&ic': product.sku,\n '&iv': `${product.category}`,\n '&ip': product.price,\n '&iq': product.quantity,\n });\n });\n\n // TODO: decide how to send large orders to Segment without sending to GA again\n return this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n this.analytics.track('Order Completed', payload);\n\n this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n trackStepViewed(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepViewed(stepId)) {\n return;\n }\n\n this.trackViewed(stepId);\n this.backfill(stepId);\n }\n\n trackStepCompleted(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepCompleted(stepId)) {\n return;\n }\n\n this.backfill(stepId);\n this.trackCompleted(stepId);\n }\n\n private backfill(stepId: AnalyticStepId): void {\n for (const i of this._analyticStepOrder) {\n const id = this.getIdFromStep(i);\n\n if (!id) {\n break;\n }\n\n if (!this.hasStepViewed(id)) {\n this.trackViewed(id);\n }\n\n if (id === stepId) {\n break;\n }\n\n if (!this.hasStepCompleted(id)) {\n this.trackCompleted(id);\n }\n }\n }\n\n private trackCompleted(stepId: AnalyticStepId): void {\n const shippingMethod = this.getSelectedShippingOption();\n const { code: currency = '' } = this.getShopperCurrency() || {};\n const paymentMethod = this.getPaymentMethodName();\n\n const payload: {\n step: number;\n currency: string;\n shipping_method?: string;\n payment_method?: string;\n } = {\n step: stepId,\n currency,\n };\n\n if (shippingMethod) {\n payload.shipping_method = shippingMethod.description;\n }\n\n if (paymentMethod) {\n payload.payment_method = paymentMethod;\n }\n\n // due to an issue with the way the segment library works, we must send at least one of the two\n // options--otherwise it rejects the track call with no diagnostic messages. however, if we blindly\n // include both options, it sends a single comma for the value, which is undesireable. by only adding\n // one of the two (shippingMethod here being arbitrarily chosen), we always have at least one value, but\n // never send two empty values.\n if (!payload.shipping_method && !payload.payment_method) {\n payload.shipping_method = ' ';\n }\n\n this.analytics.track('Checkout Step Completed', payload);\n\n const shippingMethodId = shippingMethod ? shippingMethod.id : '';\n const completedStepId =\n stepId === AnalyticStepId.SHIPPING ? `${stepId}-${shippingMethodId}` : stepId;\n\n this._completedSteps[completedStepId] = true;\n }\n\n private getTrackingPayload({\n orderId,\n revenue,\n shipping,\n tax,\n discount,\n coupons,\n extraItemsData,\n lineItems,\n }: {\n orderId?: number;\n revenue: number;\n shipping: number;\n tax: number;\n discount: number;\n coupons: Coupon[];\n extraItemsData: ExtraItemsData;\n lineItems: LineItemMap;\n }) {\n const { code = '' } = this.getShopperCurrency() || {};\n const { storeName = '' } = this.getStoreProfile() || {};\n\n return {\n order_id: String(orderId),\n affiliation: storeName,\n revenue: this.toShopperCurrency(revenue),\n shipping: this.toShopperCurrency(shipping),\n tax: this.toShopperCurrency(tax),\n discount: this.toShopperCurrency(discount),\n coupon: (coupons || []).map((coupon) => coupon.code.toUpperCase()).join(','),\n currency: code,\n products: this.getProducts(extraItemsData, lineItems),\n };\n }\n\n private hasStepCompleted(stepId: AnalyticStepId): boolean {\n const shippingOption = this.getSelectedShippingOption();\n const shippingMethodId = shippingOption ? shippingOption.id : '';\n\n return (\n Object.prototype.hasOwnProperty.call(this._completedSteps, stepId) ||\n (stepId === AnalyticStepId.SHIPPING &&\n Object.prototype.hasOwnProperty.call(\n this._completedSteps,\n `${stepId}-${shippingMethodId}`,\n ))\n );\n }\n\n private hasStepViewed(stepId: AnalyticStepId): boolean {\n return !!this._viewedSteps[stepId];\n }\n\n private getIdFromStep(step: string): AnalyticStepId | null {\n const name = step.split('.');\n\n return ANALYTIC_STEPS[name[0]] || null;\n }\n\n private trackViewed(stepId: AnalyticStepId): void {\n const currency = this.getShopperCurrency();\n\n this.analytics.track('Checkout Step Viewed', {\n step: stepId,\n currency: currency ? currency.code : '',\n });\n\n this._viewedSteps[stepId] = true;\n }\n\n private getOrder(): Order | undefined {\n const {\n data: { getOrder },\n } = this.checkoutService.getState();\n\n return getOrder();\n }\n\n private getCheckout(): Checkout | undefined {\n const {\n data: { getCheckout },\n } = this.checkoutService.getState();\n\n return getCheckout();\n }\n\n private getShopperCurrency(): ShopperCurrency | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.shopperCurrency;\n }\n\n private getStoreProfile(): StoreProfile | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.storeProfile;\n }\n\n private toShopperCurrency(amount: number): number {\n const { exchangeRate = 1 } = this.getShopperCurrency() || {};\n\n return Math.round(amount * exchangeRate * 100) / 100;\n }\n\n private getSelectedShippingOption(): ShippingOption | null {\n const { data } = this.checkoutService.getState();\n const shippingOption = data.getSelectedShippingOption();\n\n return shippingOption && shippingOption.id && shippingOption.description\n ? shippingOption\n : null;\n }\n\n private getPaymentMethodName(): string {\n const { data } = this.checkoutService.getState();\n const paymentMethod = data.getSelectedPaymentMethod();\n\n return paymentMethod && paymentMethod.config ? paymentMethod.config.displayName || '' : '';\n }\n\n private getProducts(itemsData: ExtraItemsData, lineItems: LineItemMap): AnalyticsProduct[] {\n const customItems: AnalyticsProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n price: item.listPrice,\n quantity: item.quantity,\n name: item.name,\n }));\n\n const giftCertificateItems: AnalyticsProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n price: this.toShopperCurrency(item.amount),\n name: item.name,\n quantity: 1,\n };\n });\n\n const transformItem = (item: PhysicalItem | DigitalItem): AnalyticsProduct => {\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n const variant =\n Array.isArray(itemAttributes) && itemAttributes.length\n ? itemAttributes.join(', ')\n : 'single-product-option';\n\n const brand = itemsData[item.productId] && itemsData[item.productId].brand;\n\n return {\n product_id: String(item.productId),\n sku: item.sku,\n price: item.salePrice,\n image_url: item.imageUrl,\n name: item.name,\n quantity: item.quantity,\n category: itemsData[item.productId] ? itemsData[item.productId].category : '',\n variant,\n ...(brand && { brand }),\n };\n };\n\n const physicalAndDigitalItems: AnalyticsProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map(transformItem);\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems];\n }\n}\n\nexport interface AnalyticsProduct {\n product_id: string | number;\n price: number;\n quantity: number;\n name: string;\n sku?: string;\n image_url?: string;\n category?: string;\n variant?: string;\n brand?: string;\n}\n","import StepTracker from './step-tracker';\n\nexport default class NoopStepTracker implements StepTracker {\n trackCheckoutStarted(): void {}\n\n trackOrderComplete(): void {}\n\n trackStepViewed(): void {}\n\n trackStepCompleted(): void {}\n}\n","import localStorageFallback from 'local-storage-fallback';\n\nimport {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { CheckoutService } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport AnalyticsStepTracker, { StepTrackerConfig } from './analytics-step-tracker';\nimport NoopStepTracker from './noop-step-tracker';\nimport StepTracker from './step-tracker';\n\n/**\n * Creates an instance of `StepTracker`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const stepTracker = createStepTracker(checkoutService);\n *\n * stepTracker.trackCheckoutStarted();\n * ```\n *\n * @param CheckoutService - An instance of CheckoutService\n * @param StepTrackerConfig - A step tracker config object\n * @returns an instance of `StepTracker`.\n */\nexport default function createStepTracker(\n checkoutService: CheckoutService,\n stepTrackerConfig?: StepTrackerConfig,\n): StepTracker {\n const { data } = checkoutService.getState();\n const config = data.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { isAnalyticsEnabled } = config.checkoutSettings;\n\n if (isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n return new AnalyticsStepTracker(\n checkoutService,\n new AnalyticsExtraItemsManager(localStorageFallback),\n window.analytics,\n stepTrackerConfig,\n );\n }\n\n return new NoopStepTracker();\n}\n","import { BraintreeFastlaneWindow } from '../types';\n\nexport default function isBraintreeFastlaneWindow(\n window: Window,\n): window is BraintreeFastlaneWindow {\n return Boolean(window.hasOwnProperty('braintreeFastlane'));\n}\n","import {\n BraintreeFastlane,\n BraintreeFastlaneApmSelectedEventOptions,\n BraintreeFastlaneEmailEnteredEventOptions,\n BraintreeFastlaneEventCommonOptions,\n BraintreeFastlaneOrderPlacedEventOptions,\n isBraintreeFastlaneWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutService } from '../../checkout';\n\nimport BraintreeAnalyticTrackerService from './braintree-analytic-tracker-service';\n\nexport default class BraintreeAnalyticTracker implements BraintreeAnalyticTrackerService {\n private _selectedPaymentMethodId = '';\n\n constructor(private checkoutService: CheckoutService) {}\n\n customerPaymentMethodExecuted() {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackEmailSubmitted();\n }\n }\n\n paymentComplete() {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackOrderPlaced(this._selectedPaymentMethodId);\n }\n }\n\n selectedPaymentMethod(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, false);\n }\n }\n\n walletButtonClick(methodId: string) {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, true);\n }\n }\n\n private _shouldTrackFastlaneEvent() {\n const state = this.checkoutService.getState();\n const paymentMethod =\n state.data.getPaymentMethod('braintree') ||\n state.data.getPaymentMethod('braintreeacceleratedcheckout');\n const isAnalyticEnabled = paymentMethod?.initializationData.isBraintreeAnalyticsV2Enabled;\n\n const isAvailableAnalyticEventsMethods =\n isBraintreeFastlaneWindow(window) && window.braintreeFastlane.events;\n\n return isAnalyticEnabled && isAvailableAnalyticEventsMethods;\n }\n\n private _getBraintreeEventsOrThrow(): BraintreeFastlane['events'] {\n if (isBraintreeFastlaneWindow(window)) {\n return window.braintreeFastlane.events;\n }\n\n throw new PaymentMethodClientUnavailableError();\n }\n\n /**\n *\n * Braintree Events tracking methods\n *\n */\n private _trackEmailSubmitted(): void {\n const { emailSubmitted } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getEmailSubmittedEventOptions();\n\n emailSubmitted(eventOptions);\n }\n\n private _trackApmSelected(methodId: string, isWalletButton: boolean): void {\n const { apmSelected } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getApmSelectedEventOptions(methodId, isWalletButton);\n\n apmSelected(eventOptions);\n }\n\n private _trackOrderPlaced(methodId: string): void {\n const { orderPlaced } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getOrderPlacedEventOptions(methodId);\n\n orderPlaced(eventOptions);\n }\n\n /**\n *\n * Event options methods\n *\n */\n private _getEventCommonOptions(): BraintreeFastlaneEventCommonOptions {\n const state = this.checkoutService.getState();\n const cart = state.data.getCart();\n const storeProfile = state.data.getConfig()?.storeProfile;\n const isGuestCustomer = state.data.getCustomer()?.isGuest;\n\n const paymentMethod = state.data.getPaymentMethod('braintreeacceleratedcheckout');\n const isTestTreatmentGroup =\n !state.errors.getLoadPaymentMethodError('braintreeacceleratedcheckout') &&\n paymentMethod?.initializationData.shouldRunAcceleratedCheckout;\n\n const experiments = [\n {\n treatment_group: isTestTreatmentGroup ? 'test' : 'control',\n },\n ];\n\n return {\n context_type: 'cs_id',\n context_id: cart?.id || '',\n page_type: 'checkout_page',\n page_name: window.document.title,\n partner_name: 'bigc',\n user_type: isGuestCustomer ? 'store_guest' : 'store_member',\n store_id: storeProfile?.storeId || '',\n merchant_name: storeProfile?.storeName || '',\n experiment: JSON.stringify(experiments),\n };\n }\n\n private _getEmailSubmittedEventOptions(): BraintreeFastlaneEmailEnteredEventOptions {\n const state = this.checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n user_email_saved: false,\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n };\n }\n\n private _getApmSelectedEventOptions(\n methodId: string,\n isWalletButton: boolean,\n ): BraintreeFastlaneApmSelectedEventOptions {\n const state = this.checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n apm_selected: methodId,\n apm_location: isWalletButton ? 'pre-email section' : 'payment section',\n };\n }\n\n private _getOrderPlacedEventOptions(\n methodId: string,\n ): BraintreeFastlaneOrderPlacedEventOptions {\n const state = this.checkoutService.getState().data;\n const cart = state.getCart();\n\n return {\n ...this._getEventCommonOptions(),\n selected_payment_method: methodId,\n currency_code: cart?.currency.code || '',\n };\n }\n}\n","import { CheckoutService } from '../../checkout';\n\nimport BraintreeAnalyticTracker from './braintree-analytic-tracker';\nimport BraintreeAnalyticTrackerService from './braintree-analytic-tracker-service';\n\n/**\n * Creates an instance of `BraintreeAnalyticTrackerService`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const braintreeAnalyticTracker = createBraintreeAnalyticTracker(checkoutService);\n *\n * braintreeAnalyticTracker.customerPaymentMethodExecuted();\n * braintreeAnalyticTracker.paymentComplete();\n * braintreeAnalyticTracker.selectedPaymentMethod('applepay');\n * braintreeAnalyticTracker.walletButtonClick('paypal');\n * ```\n *\n * @returns an instance of `BraintreeAnalyticTrackerService`.\n */\nexport default function createBraintreeAnalyticTracker(\n checkoutService: CheckoutService,\n): BraintreeAnalyticTrackerService {\n return new BraintreeAnalyticTracker(checkoutService);\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalCommerceHostWindow,\n PayPalFastlaneApmSelectedEventOptions,\n PayPalFastlaneEmailEnteredEventOptions,\n PayPalFastlaneEventCommonOptions,\n PayPalFastlaneEvents,\n PayPalFastlaneOrderPlacedEventOptions,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { CheckoutService } from '../../checkout';\n\nimport PayPalCommerceAnalyticTrackerService from './paypal-commerce-analytic-tracker-service';\n\nexport default class PayPalCommerceAnalyticTracker implements PayPalCommerceAnalyticTrackerService {\n private _selectedPaymentMethodId = '';\n\n constructor(private _checkoutService: CheckoutService) {}\n\n customerPaymentMethodExecuted(): void {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackEmailSubmitted();\n }\n }\n\n paymentComplete(): void {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackOrderPlaced(this._selectedPaymentMethodId);\n }\n }\n\n selectedPaymentMethod(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, false);\n }\n }\n\n walletButtonClick(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, true);\n }\n }\n\n private _shouldTrackFastlaneEvent(): boolean {\n const state = this._checkoutService.getState();\n const paymentMethod = state.data.getPaymentMethod('paypalcommerce');\n const initializationData = paymentMethod?.initializationData || {};\n const isAnalyticEnabled = initializationData.isPayPalCommerceAnalyticsV2Enabled;\n\n const paypalHostWindow = window as PayPalCommerceHostWindow;\n const isAvailableAnalyticEventsMethods = paypalHostWindow.paypalFastlane\n ? !!paypalHostWindow.paypalFastlane.events\n : false;\n\n return isAnalyticEnabled && isAvailableAnalyticEventsMethods;\n }\n\n private _getPayPalEventsOrThrow(): PayPalFastlaneEvents {\n const paypalHostWindow = window as PayPalCommerceHostWindow;\n\n if (paypalHostWindow.paypalFastlane && paypalHostWindow.paypalFastlane.events) {\n return paypalHostWindow.paypalFastlane.events;\n }\n\n throw new PaymentMethodClientUnavailableError();\n }\n\n /**\n *\n * Analytic Event track methods\n *\n */\n private _trackEmailSubmitted(): void {\n const { emailSubmitted } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getEmailSubmittedEventOptions();\n\n emailSubmitted(eventOptions);\n }\n\n private _trackApmSelected(methodId: string, isWalletButton: boolean): void {\n const { apmSelected } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getApmSelectedEventOptions(methodId, isWalletButton);\n\n apmSelected(eventOptions);\n }\n\n private _trackOrderPlaced(methodId: string): void {\n const { orderPlaced } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getOrderPlacedEventOptions(methodId);\n\n orderPlaced(eventOptions);\n }\n\n /**\n *\n * Event options methods\n *\n */\n private _getEventCommonOptions(): PayPalFastlaneEventCommonOptions {\n const state = this._checkoutService.getState();\n const cart = state.data.getCart();\n const storeProfile = state.data.getConfig()?.storeProfile;\n const isGuestCustomer = state.data.getCustomer()?.isGuest;\n const methodId = 'paypalcommerceacceleratedcheckout';\n\n const paymentMethod = state.data.getPaymentMethod(methodId);\n const isTestTreatmentGroup =\n !state.errors.getLoadPaymentMethodError(methodId) &&\n paymentMethod?.initializationData.shouldRunAcceleratedCheckout;\n\n const experiments = [\n {\n treatment_group: isTestTreatmentGroup ? 'test' : 'control',\n },\n ];\n\n return {\n context_type: 'cs_id',\n context_id: cart?.id.replace(/-/g, '') || '',\n page_type: 'checkout_page',\n page_name: window.document.title,\n partner_name: 'bigc',\n user_type: isGuestCustomer ? 'store_guest' : 'store_member',\n store_id: storeProfile?.storeId || '',\n merchant_name: storeProfile?.storeName || '',\n experiment: JSON.stringify(experiments),\n };\n }\n\n private _getEmailSubmittedEventOptions(): PayPalFastlaneEmailEnteredEventOptions {\n const state = this._checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n user_email_saved: false,\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n };\n }\n\n private _getApmSelectedEventOptions(\n methodId: string,\n isWalletButton: boolean,\n ): PayPalFastlaneApmSelectedEventOptions {\n const state = this._checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n apm_selected: methodId,\n apm_location: isWalletButton ? 'pre-email section' : 'payment section',\n };\n }\n\n private _getOrderPlacedEventOptions(methodId: string): PayPalFastlaneOrderPlacedEventOptions {\n const state = this._checkoutService.getState().data;\n const cart = state.getCart();\n\n return {\n ...this._getEventCommonOptions(),\n selected_payment_method: methodId,\n currency_code: cart?.currency.code || '',\n };\n }\n}\n","import { CheckoutService } from '../../checkout';\n\nimport PayPalCommerceAnalyticTracker from './paypal-commerce-analytic-tracker';\nimport PayPalCommerceAnalyticTrackerService from './paypal-commerce-analytic-tracker-service';\n\n/**\n * Creates an instance of `PayPalCommerceAnalyticTrackerService`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const paypalCommerceAnalyticTracker = createPayPalCommerceAnalyticTracker(checkoutService);\n *\n * paypalCommerceAnalyticTracker.customerPaymentMethodExecuted();\n * paypalCommerceAnalyticTracker.paymentComplete();\n * paypalCommerceAnalyticTracker.selectedPaymentMethod('applepay');\n * paypalCommerceAnalyticTracker.walletButtonClick('paypal');\n * ```\n *\n * @returns an instance of `PayPalCommerceAnalyticTrackerService`.\n */\nexport default function createPayPalCommerceAnalyticTracker(\n checkoutService: CheckoutService,\n): PayPalCommerceAnalyticTrackerService {\n return new PayPalCommerceAnalyticTracker(checkoutService);\n}\n","import { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport HostedForm from './hosted-form';\nimport HostedFormFactory from './hosted-form-factory';\nimport LegacyHostedFormOptions from './hosted-form-options';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport default class StoredCardHostedFormService {\n protected _hostedForm?: HostedForm;\n constructor(protected _host: string, protected _hostedFormFactory: HostedFormFactory) {}\n\n async submitStoredCard(\n fields: StoredCardHostedFormInstrumentFields,\n data: StoredCardHostedFormData,\n ): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate().then(() => form.submitStoredCard({ fields, data }));\n }\n\n initialize(options: LegacyHostedFormOptions): Promise {\n const form = this._hostedFormFactory.create(this._host, options);\n\n return form.attach().then(() => {\n this._hostedForm = form;\n });\n }\n\n deinitialize() {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { createCheckoutStore } from '../checkout';\n\nimport HostedFormFactory from './hosted-form-factory';\nimport StoredCardHostedFormService from './stored-card-hosted-form-service';\n\n/**\n * Creates an instance of `StoredCardHostedFormService`.\n *\n *\n * @param host - Host url string parameter.\n * @returns An instance of `StoredCardHostedFormService`.\n */\nexport default function createStoredCardHostedFormService(host: string) {\n const store = createCheckoutStore();\n\n return new StoredCardHostedFormService(host, new HostedFormFactory(store));\n}\n","export enum AnalyticStepType {\n CUSTOMER = 'customer',\n SHIPPING = 'shipping',\n BILLING = 'billing',\n PAYMENT = 'payment',\n}\n\nexport const AnalyticStepOrder: AnalyticStepType[] = [\n AnalyticStepType.CUSTOMER,\n AnalyticStepType.SHIPPING,\n AnalyticStepType.BILLING,\n AnalyticStepType.PAYMENT,\n];\n","import { flatten } from 'lodash';\n\nimport { LineItem, LineItemMap } from '../cart';\nimport { CheckoutSelectors, CheckoutStoreSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { AnalyticStepOrder, AnalyticStepType } from './analytics-steps';\nimport BodlService from './bodl-service';\nimport {\n BodlEventsCheckout,\n BodlEventsPayload,\n BODLProduct,\n CommonCheckoutData,\n} from './bodl-window';\n\nexport default class BodlEmitterService implements BodlService {\n private _checkoutStarted = false;\n private _emailEntryBegan = false;\n private _shippingOptionsShown = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private state?: CheckoutStoreSelector;\n\n constructor(\n private subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n private bodlEvents: BodlEventsCheckout,\n ) {\n this.subscribe((state) => {\n this.setState(state.data);\n\n const config = this.state?.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n });\n }\n\n setState(state: CheckoutStoreSelector) {\n this.state = state;\n }\n\n checkoutBegin(): void {\n const data = this._getCommonCheckoutData();\n\n if (this._checkoutStarted || !data) {\n return;\n }\n\n this.bodlEvents.emitCheckoutBeginEvent(data);\n\n this._checkoutStarted = true;\n }\n\n orderPurchased(): void {\n const order = this.state?.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n currency,\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n lineItems,\n cartId,\n coupons,\n channelId,\n taxTotal,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n this.bodlEvents.emitOrderPurchasedEvent({\n event_id: cartId,\n currency: currency.code,\n order_id: orderId,\n tax: taxTotal,\n channel_id: channelId,\n cart_value: orderAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n shipping_cost: shippingCostTotal,\n line_items: this._getProducts(lineItems, currency.code),\n });\n }\n\n stepCompleted(currentStep?: AnalyticStepType): void {\n if (!currentStep) {\n return;\n }\n\n AnalyticStepOrder.some((step: AnalyticStepType) => {\n if (!this._hasStepCompleted(step)) {\n this._trackCompletedStep(step);\n }\n\n return step === currentStep;\n });\n }\n\n customerEmailEntry(email?: string) {\n if (this._emailEntryBegan || !email?.length) {\n return;\n }\n\n this._emailEntryBegan = true;\n this.bodlEvents.emit('bodl_checkout_email_entry_began');\n }\n\n customerSuggestionInit(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_initialization', payload);\n }\n\n customerSuggestionExecute() {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_execute');\n }\n\n customerPaymentMethodExecuted(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_payment_method_executed', payload);\n }\n\n showShippingMethods() {\n if (this._shippingOptionsShown) {\n return;\n }\n\n this._shippingOptionsShown = true;\n this.bodlEvents.emit('bodl_checkout_show_shipping_options');\n }\n\n selectedPaymentMethod(paymentOption?: string) {\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !paymentOption) {\n return;\n }\n\n this.bodlEvents.emitPaymentDetailsProvidedEvent({\n ...commonData,\n payment_type: paymentOption,\n });\n }\n\n clickPayButton(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_click_pay_button', payload);\n }\n\n paymentRejected() {\n this.bodlEvents.emit('bodl_checkout_payment_rejected');\n }\n\n paymentComplete() {\n this.bodlEvents.emit('bodl_checkout_payment_complete');\n }\n\n exitCheckout() {\n this.bodlEvents.emit('bodl_checkout_exit');\n }\n\n private _trackCompletedStep(step: AnalyticStepType) {\n this._completedSteps[step] = true;\n\n const bodlEventsMap: { [key in AnalyticStepType]?: () => void } = {\n [AnalyticStepType.SHIPPING]: this._trackShippingStepCompleted.bind(this),\n };\n const emit = bodlEventsMap[step];\n\n if (emit) {\n emit();\n } else {\n this.bodlEvents.emit('bodl_checkout_step_completed', { step });\n }\n }\n\n private _trackShippingStepCompleted(): void {\n const shippingMethod = this.state?.getSelectedShippingOption()?.description;\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !shippingMethod) {\n return;\n }\n\n this.bodlEvents.emitShippingDetailsProvidedEvent({\n ...commonData,\n shipping_method: shippingMethod,\n });\n }\n\n private _getCommonCheckoutData(): CommonCheckoutData | null {\n const checkout = this.state?.getCheckout();\n\n if (!checkout) {\n return null;\n }\n\n const {\n cart: { cartAmount, currency, lineItems, id, coupons },\n channelId,\n } = checkout;\n\n return {\n event_id: id,\n currency: currency.code,\n cart_value: cartAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n line_items: this._getProducts(lineItems, currency.code),\n channel_id: channelId,\n };\n }\n\n private _getProducts(lineItems: LineItemMap, currencyCode: string): BODLProduct[] {\n const customItems: BODLProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n base_price: item.listPrice,\n sale_price: item.listPrice,\n purchase_price: item.listPrice,\n quantity: item.quantity,\n product_name: item.name,\n currency: currencyCode,\n }));\n\n const giftCertificateItems: BODLProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n gift_certificate_id: item.id,\n base_price: item.amount,\n sale_price: item.amount,\n purchase_price: item.amount,\n product_name: item.name,\n gift_certificate_name: item.name,\n gift_certificate_theme: item.theme,\n quantity: 1,\n currency: currencyCode,\n };\n });\n\n const physicalAndDigitalItems: BODLProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n const getCategoryNames = (lineItem: LineItem): string[] => {\n if (Array.isArray(lineItem.categoryNames)) {\n return lineItem.categoryNames;\n } else if (Array.isArray(lineItem.categories)) {\n return flatten(lineItem.categories).map(({ name }) => name);\n }\n\n return [];\n };\n\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n quantity: item.quantity,\n product_name: item.name,\n base_price: item.listPrice,\n sale_price: item.salePrice,\n purchase_price: item.salePrice > 0 ? item.salePrice : item.listPrice,\n sku: item.sku,\n variant_id: item.variantId,\n discount: item.discountAmount,\n coupon_amount: item.couponAmount,\n brand_name: item.brand,\n currency: currencyCode,\n category_names: getCategoryNames(item),\n retail_price: item.retailPrice,\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems].map(\n (item) => ({\n ...item,\n product_id: String(item.product_id),\n }),\n );\n }\n\n private _hasStepCompleted(step: AnalyticStepType): boolean {\n return this._completedSteps[step];\n }\n}\n","import BodlService from './bodl-service';\n\nexport default class NoopBodlService implements BodlService {\n checkoutBegin(): void {}\n\n orderPurchased(): void {}\n\n stepCompleted(): void {}\n\n customerEmailEntry(): void {}\n\n customerSuggestionInit(): void {}\n\n customerSuggestionExecute(): void {}\n\n customerPaymentMethodExecuted(): void {}\n\n showShippingMethods(): void {}\n\n selectedPaymentMethod(): void {}\n\n clickPayButton(): void {}\n\n paymentRejected(): void {}\n\n paymentComplete(): void {}\n\n exitCheckout(): void {}\n}\n","import { CheckoutSelectors } from '../checkout';\n\nimport BodlEmitterService from './bodl-emitter-service';\nimport BodlService from './bodl-service';\nimport { isBodlEnabled } from './is-bodl-enabled';\nimport NoopBodlService from './noop-bodl-service';\n\n/**\n * Creates an instance of `BodlService`.\n *\n * @remarks\n *\n * ```js\n * const bodlService = BodlService();\n * bodlService.checkoutBegin();\n *\n * ```\n *\n * @param subscribe - The callback function, what get a subscriber as a property, that subscribes to state changes.\n * @returns an instance of `BodlService`.\n */\nexport default function createBodlService(\n subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n): BodlService {\n if (isBodlEnabled(window)) {\n return new BodlEmitterService(subscribe, window.bodlEvents.checkout);\n }\n\n return new NoopBodlService();\n}\n","import BodlEventsWindow from './bodl-window';\n\nexport function isBodlEnabled(window: Window): window is BodlEventsWindow {\n return 'bodlEvents' in window;\n}\n"],"names":["module","exports","require","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","throwErrorAction","type","error","meta","action","concat","of","throwError","createErrorAction","payload","message","object","name","setPrototypeOf","__proto__","Error","captureStackTrace","stack","MissingDataErrorType","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","BillingAddressActionType","_requestSender","_subscriptionActionCreator","continueAsGuest","credentials","options","store","state","getState","checkout","getCheckout","isBillingFixExperimentEnabled","config","getConfig","storeConfig","checkoutSettings","features","customer","getCustomer","isGuest","billingAddressRequestBody","billingAddress","getBillingAddress","existingBillingAddressRequestBody","hasBillingAddress","isEmpty","merge","createAction","ContinueAsGuestRequested","defer","this","_createOrUpdateBillingAddress","id","body","ContinueAsGuestSucceeded","pipe","catchError","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","Observable","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","empty","updateSubscriptions","checkoutId","createAddress","ContentType","SDK_VERSION_HEADERS","DEFAULT_PARAMS","include","join","timeout","url","headers","Accept","JsonV1","post","params","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","createDataStore","Synchronize","subscribe","dispatch","initial","clearError","ClearError","getEnvironment","process","env","NODE_ENV","e","_console","log","_logToConsole","messages","info","warn","debug","isEnabled","logger","console","getDefaultLogger","ConfigActionType","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","param","lastArg","args","length","useCache","fn","instanceMethods","set","memoize","from","shareReplay","isEqual","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","DEFAULT_RESPONSE","status","errors","title","INTERNAL_USE_ONLY","CouponActionType","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","CheckoutIncludes","joinIncludes","includes","uniq","couponCode","AvailableShippingOptions","delete","GiftCertificateActionType","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","giftCertificateCode","isResolvableModule","_factories","_instances","_defaultToken","defaultToken","_useFallback","useFallback","_tokenResolver","tokenResolver","token","cacheToken","_getInstance","register","factory","_hasFactory","_hasInstance","resolvedToken","keys","_registry","_resolveToken","bind","resolveId","_encodeToken","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","default","entries","push","matchedResults","sort","b","filter","matched","find","getShippableItemsCount","cart","lineItems","physicalItems","item","addedByPromotion","reduce","total","quantity","guard","errorFactory","NotInitializedErrorType","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","amazonPayV2Regions","de","jp","uk","us","amazonPayV2ScriptLoader","initialize","paymentMethod","load","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","deinitialize","amazonPayV2Button","remove","Promise","resolve","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","containerId","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","methodId","placement","isButtonMicroTextDisabled","container","document","querySelector","parentContainerId","appendChild","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","isEnvironmentSpecific","uid","Math","random","toString","substr","parentContainer","createElement","Gold","getCheckoutState","getCart","getStoreConfigOrThrow","getPaymentMethodOrThrow","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","storeProfile","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","test","getOrThrow","checkoutSelectors","paymentMethods","scriptLoader","windowWithAmazonPay","window","region","amazonPayV2Region","loadScript","amazon","createAmazonPayV2PaymentProcessor","getScriptLoader","toResolvableModule","resolveIds","assign","paymentIntegrationService","amazonPayV2PaymentProcessor","amazonpay","loadPaymentMethod","Checkout","signIn","signOut","payment","getPaymentId","remoteCheckoutSignOut","providerId","executePaymentMethodCheckout","continueWithCheckoutCallback","TotalPriceStatusType","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","NonInstantLocalPaymentMethods","isBraintreeError","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","loadClient","clientCreator","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","teardown","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","all","loadGooglePayment","braintreeGooglePayment","getBraintreeThreeDS","threeDS","load3DS","threeDSecure","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","loadLocalPayment","reject","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","loadVenmoCheckout","venmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","braintreeHostWindow","braintreeSdkVersion","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","hash","async","attributes","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","scriptPath","getIntegrityValuesByModuleName","braintree","moduleName","ApplePayGatewayType","assertApplePayWindow","isApplePayWindow","request","ApplePaySession","DefaultLabels","_paymentIntegrationService","_sessionFactory","_braintreeSdk","_onAuthorizeCallback","noop","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","_paymentMethod","verifyCheckoutSpamProtection","_applePayButton","_createButton","addEventListener","_handleWalletButtonClick","gateway","BRAINTREE","_initializeBraintreeSdk","getElementById","button","setAttribute","event","preventDefault","getCartOrThrow","getCheckoutOrThrow","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","label","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","_onValidateMerchant","merchantSession","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","loadCheckout","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","consignments","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","Array","completeShippingContactSelection","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","hostname","bigPayEndpoint","paymentsUrl","billingContact","_getBraintreeDeviceData","deviceSessionId","formattedPayload","apple_pay_token","payment_data","payment_method","transaction_id","transactionIdentifier","transformedBillingAddress","transformedShippingAddress","emailAddress","phone","phoneNumber","updateBillingAddress","submitOrder","useStoreCredit","submitPayment","completePayment","STATUS_SUCCESS","STATUS_FAILURE","contact","firstName","givenName","lastName","familyName","city","locality","company","address1","addressLines","address2","postalCode","stateOrProvince","administrativeArea","stateOrProvinceCode","customFields","braintreePaymentMethod","getPaymentMethod","getHost","createRequestSender","host","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","signInCustomer","signOutCustomer","checkoutPaymentMethodExecuted","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","BoltCheckout","BoltDeveloperMode","StyleButtonSize","StyleButtonShape","developerModeParams","cartId","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","PAYPAL_COMPONENTS","overlay","dataCollectors","getBraintreeFastlane","cardId","isTestModeEnabled","styles","localStorage","setItem","braintreeFastlane","getSessionId","braintreeFastlaneCreator","defaultStyles","root","backgroundColorPrimary","getPaypal","braintreePaypal","paypal","shouldSaveInstrument","newWindowFlow","supportsPopups","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","paypalCheckoutCallback","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","components","intent","commit","loadPayPalSDK","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","details","split","first_name","last_name","phone_number","address_line_1","address_line_2","country_code","postal_code","mapToLegacyBillingAddress","removeElement","elementId","element","riskCorrelationId","formPoster","braintreeIntegrationService","braintreepaypal","paymentButtonStyles","checkoutTopButtonStyles","paypalCheckoutOptions","paypalCheckoutSuccessCallback","renderPayPalButton","paypalCheckoutErrorCallback","handleError","buttonStyles","fundingSource","FUNDING","PAYPAL","paypalButtonRender","Buttons","style","height","createOrder","setupPayment","onApprove","authorizeData","tokenizePayment","isEligible","render","loadDefaultCheckout","addresses","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","nonce","postForm","payment_type","provider","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","createFormPoster","braintreepaypalcredit","hasRenderedSmartButton","PAYLATER","CREDIT","namespace","getItem","rawValue","withNamespace","removeItem","getItemOnce","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","omitBy","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","borderRadius","fastlaneInputSettingsBorderRadius","borderColor","fastlaneInputSettingsBorderColor","focusBorderColor","fastlaneInputSettingsFocusBorderBase","backgroundColor","fastlaneInputSettingsBackgroundColor","borderWidth","fastlaneInputSettingsBorderWidth","textColorBase","fastlaneInputSettingsTextColorBase","colorPrimary","fastlaneToggleSettingsColorPrimary","colorSecondary","fastlaneToggleSettingsColorSecondary","color","fastlaneTextBodySettingsColor","fontSize","fastlaneTextBodySettingsFontSize","fastlaneTextCaptionSettingsColor","fastlaneTextCaptionSettingsFontSize","fastlaneBrandingSettings","mergeFastlaneStyles","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","isFastlaneStylingEnabled","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","getCustomerOrThrow","shouldRunAuthenticationFlow","runPayPalAuthenticationFlowOrThrow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","UntrustedShippingCardVerificationType","browserStorage","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlow","isFastlaneShippingOptionAutoSelectEnabled","customerEmail","customerContextId","updatePaymentProviderCustomer","authenticationState","UNRECOGNIZED","instruments","profileData","CANCELED","shippingAddresses","mapPayPalToBcAddress","paypalBillingAddress","getPayPalBillingAddresses","billingAddresses","card","mapPayPalToBcInstrument","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","map","instrument","brand","expiry","lastDigits","expiryYear","bigpayToken","defaultInstrument","expiryMonth","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","phones","countries","getCountries","Date","now","streetAddress","extendedAddress","country","countryCodeAlpha2","matchedCountry","paymentSource","given_name","surname","normalizeAddress","omit","filteredBillingAddresses","some","getConsignments","recommendedShippingOption","braintreeSdk","buttonClassName","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","String","settings","locale","storeLanguage","shipping","collectShipping","signInButton","createSignInButton","init","on","paymentSuccessPayload","visibility","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","number","lastTwo","getAddress","buttonClass","insertVisaCheckoutButton","buttonTemplate","visaCheckoutButton","display","flexDirection","width","className","innerHTML","hostWindow","target","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","_toFixed","integerAmount","decimalAmount","parsedIntegerAmount","replace","toLowerCase","precision","round","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","CurrencyService","lineItem","isShippingRequired","customItems","PayPalCommerceIntent","StyleButtonLabel","StyleButtonColor","GooglePayCardNetwork","CallbackIntentsType","CallbackTriggerType","isGooglePayCardNetworkKey","_gatewayIdentifier","_isBuyNowFlow","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","cart_id","getRequiredData","data","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","getGooglePayInitializationData","merchantName","authJwt","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","totalPriceStatus","ESTIMATED","totalPrice","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","consignment","_currencyService","_getGooglePayShippingOption","shippingOption","selectedShippingOptionId","handleShippingOptionChange","defaultSelectedOptionId","getTotalPrice","getGatewayIdentifier","setGatewayIdentifier","getStoreConfig","address3","_getFirstAndLastName","trim","fullName","nameParts","slice","isGooglePayErrorObject","GooglePayKey","isGooglePayKey","values","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","err","statusCode","showPaymentSheet","siteLink","pathname","links","setExternalCheckoutForm","_scriptLoader","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","getGooglePaymentsClient","_paymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","merchantInfo","_paymentDataRequest","callbackIntents","_isReadyToPayRequest","_getOrThrow","_window","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","requestSender","service","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","Json","invalidFields","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","stripePublishableKey","stripeConnectedAccount","isStripeGooglePay3dsExperimentIsOn","loadStripeJs","stripeUPEClient","clientSecret","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getStripeClient","stripeError","payment_intent","last_payment_error","indexOf","stripeWindow","stripeAccount","stripeClient","bcStripeClient","stripe","betas","Stripe","promise","cancellable","cancel","race","_service","_braintreeGooglePayment","bin","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","verifyCard","onLookupComplete","_data","paypalCommerceScriptLoader","isGooglePayPaypalCommercePaymentMethod","assertsIsGooglePayPayPalCommercePaymentMethod","getPayPalSDK","getGooglePayConfigOrThrow","googlepayConfig","initializesOnCheckoutPage","forceLoad","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","Googlepay","transformConfig","scriptQuery","URLSearchParams","scriptSrc","clientId","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","shouldEnableCard","enableCardFunding","disableCardFunding","cardFieldsComponent","enableCreditFunding","disableCreditFunding","shouldEnableAPMs","enableVenmoFunding","disableVenmoFunding","enableAPMsFunding","disableAPMsFunding","apm","disableFunding","enableFunding","googlePayComponent","transformedConfig","isArray","getBrowserInfo","language","navigator","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","browser_info","errorBody","isObject","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","threeDSSessionData","creq","CartSource","LiabilityShiftEnum","NonInstantAlternativePaymentMethods","PayPalOrderStatus","paypalCommerceRequestSender","loadPayPalSdk","providedCurrencyCode","paypalSdk","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","requestBody","createOrderCardFields","orderId","setupToken","updateOrder","getConsignmentsOrThrow","getOrderStatus","order_id","source","BuyNow","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","shippingOptionToSelect","getBillingAddressFromOrderDetails","payer","email_address","admin_area_2","admin_area_1","getShippingAddressFromOrderDetails","orderDetails","getValidButtonStyle","shape","validStyles","getValidHeight","isNil","paypalCommerceIntegrationService","paypalcommerce","onComplete","defaultCallbacks","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","paypalButton","order","paypalcommercecredit","paypalCommerceCredit","fundingSources","paypalcommercevenmo","VENMO","getPayPalFastlaneSdk","paypalFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalApmsSdk","paypalApms","getPayPalApmSdkConfiguration","getPayPalMessages","paypalMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","connectClientToken","createPayPalCommerceSdk","createScriptLoader","PayPalFastlaneAuthenticationState","initializePayPalFastlane","paypalFastlane","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","triggerAuthenticationFlowOrThrow","updateStorageSessionId","shouldBeRemoved","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","paypalShippingAddress","paypalProfileName","paypalInstrument","filterAddresses","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","phoneData","nationalNumber","customerAddresses","currentAddress","customerAddress","isEqualAddresses","firstAddress","secondAddress","createPayPalCommerceFastlaneUtils","paypalCommerceSdk","paypalCommerceFastlaneUtils","paypalcommercefastlane","isAuthenticationFlowCanceled","updateCustomerDataState","updatedState","firstShippingOption","shippingOptionId","isStripeAcceleratedCheckoutCustomer","isStripeUPEPaymentMethodLike","shopperLanguage","StripeFormMode","DisplayName","StripePaymentMethodType","StripeStringConstants","StripeElementType","StripeUPEPaymentIntentStatus","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripePaymentProviderCustomer","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","getElements","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","authenticated","deleteConsignment","mount","unmount","stripeElements","bcStripeElements","elements","updateStripeElements","update","fetchUpdates","createCustomerStrategyRegistry","customerStrategyFactories","registry","createCustomerStrategy","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerActionType","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","createAccount","switchMap","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","CreateCustomerAddressRequested","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","SignInCustomerRequested","SignInCustomerSucceeded","SignInCustomerFailed","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerStrategyActionType","_strategyRegistry","_strategyRegistryV2","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","SignOutRequested","SignOutSucceeded","SignOutFailed","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","includesDictionary","deletions","pickBy","additions","difference","mergeIncludes","updateCheckout","CheckoutActionType","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_shouldTransformCustomerAddress","_transformCustomerAddresses","LoadCheckoutFailed","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","shouldSaveAddress","FormFieldsActionType","_formFieldsRequestSender","LoadFormFieldsRequested","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","PaymentMethodActionType","isPaymentMethod","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","loadPaymentMethods","sessionHash","methods","filteredMethods","_filterApplePay","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","cartA","cartB","_normalize","cartAmount","itemA","itemB","productId","variantId","localeCompare","extendedSalePrice","giftCertificates","recipient","giftWrapping","previous","updated","validate","comparator","_compareCoupons","coupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","_mutationObserver","ensurePresence","targets","mutationsList","mutation","removedNodes","node","contains","observe","childList","subtree","output","disconnect","callback","MutationObserver","parseUrl","anchor","href","port","origin","protocol","search","isIframeEvent","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","fromEvent","successType","errorType","take","toPromise","postMessage","setTarget","setContext","appendWww","sourceOrigin","_sourceOrigins","_isListening","_listeners","listen","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","removeListener","index","splice","trigger","messageEvent","_googleRecaptcha","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","additional_action_required","_performRecaptcha","human_verification_token","recaptchaSitekey","cardingProtectionElementId","cardingProtectionElement","parentNode","removeChild","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","event$","Subject","_widgetId","size","getResponse","reset","_event$","_recaptcha","retryWhen","delay","TIMEOUT","_watchRecaptchaChallengeWindow","iframeContainer","parentElement","attributeFilter","_loadPromise","_loadScript","callbackName","grecaptcha","createSpamProtection","MutationObserverFactory","mapFromPaymentErrorResponse","joinErrors","flatMap","fieldErrors","HostedFieldEventType","HostedInputEventType","_type","_containerId","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_cardInstrument","_iframe","src","border","overflow","getType","attach","contentWindow","AttachRequested","accessibilityLabel","cardInstrument","fontUrls","_getFontUrls","placeholder","AttachSucceeded","AttachFailed","detach","submitForm","fields","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","Validated","isValid","querySelectorAll","link","family","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","_handleEnter","onBlur","onCardTypeChange","onFocus","onValidate","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getBin","getCardType","field","_getFirstField","otherFields","without","otherField","submit","additionalActionData","transform","additionalAction","submitStoredCard","isVaultedInstrument","instrumentId","_store","instrumentMeta","getInstrumentsMeta","getOrder","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","getPaymentToken","vaultAccessToken","fieldOptions","_getCardInstrument","pick","getCardInstrument","MissingPaymentInstrument","OrderActionType","_orderRequestSender","_checkoutValidator","loadOrder","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","loadCurrentOrder","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","checkoutVariant","SubmitOrderSucceeded","SubmitOrderFailed","finalizeOrder","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","PaymentActionType","_paymentRequestSender","_orderActionCreator","_paymentRequestTransformer","initializeOffsitePayment","shouldSetAsDefaultInstrument","bigpay_token","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","SubmitPaymentSucceeded","SubmitPaymentFailed","_client","_transformResponse","statusText","createPaymentClient","paymentClient","setHost","paymentSettings","bigpayBaseUrl","mapToInternalAddress","addressId","isBillingAddressLike","province","provinceCode","postCode","toInteger","couponTypes","mapToInternalCoupon","coupon","discount","displayName","discountType","couponType","mapToInternalGiftCertificate","discountedAmount","used","remainingBalance","remaining","balance","purchaseDate","CheckoutButtonMethodType","mapToInternalLineItems","itemMap","idKey","amountTransformer","imageUrl","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","discountAmount","listPrice","salePrice","downloadsPageUrl","downloadPageUrl","sku","categoryNames","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","promotions","notifications","items","sum","discountNotifications","promotion","banners","banner","placeholders","messageHtml","totalDiscountedAmount","certificate","appliedGiftCertificates","keyBy","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","required","storeCredit","taxSubtotal","taxTotal","handling","handlingCostTotal","mapToInternalCustomer","customerId","customerGroupName","customerGroup","RegExp","month","year","trimmedMonth","trimmedYear","toObject","maxLength","max","creditCardType","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","orderToken","callbackUrl","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","step","helpText","instructions","returnUrl","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","_cardExpiryFormatter","_cardNumberFormatter","formattedInstrument","_mapShippingAddress","getShippingOption","contextConfig","paymentMeta","internalCustomer","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","ccCvv","cardCodeVerification","ccNumber","cardNumberVerification","hostedFormNonce","cardCode","ccExpiry","cardExpiry","ccName","cardName","cardNumber","isBopisEnabled","bopis","enabled","requiredAddress","isPickup","every","selectedPickupOption","PaymentProviderCustomerType","providerCustomerData","UpdatePaymentProviderCustomer","PaymentStrategyActionType","RemoteCheckoutActionType","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","initializePayment","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","forgetCheckout","ForgetCheckoutRemoteCustomerRequested","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionType","_consignmentRequestSender","unassignItemsByAddress","_consignmentHasAddress","existingConsignment","getConsignmentByAddress","_removeLineItems","updateConsignment","assignItemsByAddress","_createOrUpdateConsignment","_addLineItems","consignmentUpdateBody","consignmentMeta","UpdateShippingOptionRequested","UpdateShippingOptionSucceeded","UpdateShippingOptionFailed","loadShippingOptions","LoadShippingOptionsRequested","LoadShippingOptionsSucceeded","LoadShippingOptionsFailed","_getUpdateAddressRequestBody","createConsignments","CreateConsignmentsRequested","CreateConsignmentsSucceeded","CreateConsignmentsFailed","UpdateConsignmentRequested","UpdateConsignmentSucceeded","UpdateConsignmentFailed","consignmentId","DeleteConsignmentRequested","DeleteConsignmentSucceeded","DeleteConsignmentFailed","updateShippingOption","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","DEFAULT_INCLUDES","ShippingCountryActionType","_shippingCountryRequestSender","loadCountries","checkoutData","channelId","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","_config","channelIdParam","SpamProtectionActionType","spamProtectionElementId","spamProtectionElement","googleRecaptchaSitekey","VerifyCheckoutRequested","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","ExecuteSucceeded","ExecuteFailed","StoreCreditActionType","_storeCreditRequestSender","applyStoreCredit","ApplyStoreCreditRequested","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","SubscriptionsActionType","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","isPlainObject","cloneDeep","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getBillingAddressOrThrow","getOutstandingBalance","getLocale","getCardInstrumentOrThrow","getInstruments","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatus","getPaymentStatusOrThrow","getPaymentRedirectUrl","getPaymentRedirectUrlOrThrow","isPaymentDataRequired","getPaymentProviderCustomer","isPaymentMethodInitialized","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","_storeProjectionFactory","_hostedFormFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_paymentActionCreator","_customerActionCreator","_cartRequestSender","_storeCreditActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_paymentStrategyWidgetActionCreator","_storeProjection","createHostedForm","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","validateCheckout","handlePaymentHumanVerification","queueId","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","hostedFormFactory","orderActionCreator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","_braintreeScriptLoader","_dataCollectors","_clientToken","_getPayPalSDKConfig","_paypalCheckout","getVenmoCheckout","_venmoCheckout","venmoCheckoutCallback","get3DS","_3ds","getVisaCheckout","_visaCheckout","createHostedFields","_teardown","mod","_braintreeSDKCreator","handleSuccess","tokenizedPayload","_toVisaCheckoutAddress","_postForm","_getCardInformation","_getAddress","createBraintreeVisaCheckoutPaymentProcessor","braintreeSDKCreator","useMasterpassSrc","subdomain","sourceUrl","masterpass","_customerStrategyActionCreator","_braintreeVisaCheckoutPaymentProcessor","_visaCheckoutScriptLoader","_buttonClassName","_createSignInButton","_paymentInstrumentSelected","_onPaymentSelectComplete","_insertVisaCheckoutButton","getCallbackUrl","supportedLocales","es","en","pt","zu","ar","zh","ms","sv","hr","pl","nl","it","fr","formatLocale","localeLanguage","formattedLocale","countryLocales","_masterpassScriptLoader","_locale","masterpassOptions","allowedCardTypes","suppressShippingAddress","masterpassScriptLoaderParams","isMasterpassSrcEnabled","Masterpass","_signInButton","ExtensionActionType","ExtensionInternalEventType","createExtensionEventPoster","extension","iframe","ExtensionNotFoundError","iframeResizer","originalIframeResizer","ExtensionInternalCommandType","_options","createFrame","initCallback","failedCallback","ExtensionNotLoadedError","_toResizableFrame","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","clearTimeout","ExtensionCommandType","_extension","parentOrigin","_url","URL","searchParams","iframeCreator","iframeResizerCallback","ExtensionReady","ExtensionFailed","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","checkoutLink","getExtensionByRegion","RenderExtensionRequested","ExtensionIframe","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionEventType","_posters","extensionId","command","commandHandler","_getExtensionById","validCommandType","_validateCommand","commandHandlerProxy","getExtensions","_extensions","UnsupportedExtensionCommandError","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getInitialConsignments","currentConsignments","ConsignmentsChanged","previousConsignments","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","isCardState","encryptedSecurityCode","encryptedExpiryMonth","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","translations","_adyenClient","_mountPaymentComponent","_paymentComponent","CreditCard","Bancontact","_mountCardVerificationComponent","_cardVerificationComponent","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","_processAdditionalAction","credit_card_token","finalize","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentPayload","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","cardVerificationComponent","adyenClient","cardVerificationContainerId","SecuredFields","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","cardComponent","componentRef","showValidation","issuer","props","_mapCardErrors","cardStateErrors","getStylesheetLoader","isHostedInstrumentLike","adyenv3","installmentOptions","paymentMethodsConfiguration","klarna","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","showPayButton","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","showBrandsUnderCardNumber","showEmailAddress","onSubmit","adyenComponent","affirmScriptLoader","affirm","initializeAffirmCheckout","affirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","reason","successObject","ui","retrievedShippingAddress","merchant","user_confirmation_url","user_cancel_url","user_confirmation_url_action","getItems","metadata","shipping_type","getShippingType","platform_type","platform_version","platform_affirm","discounts","getDiscounts","shipping_amount","tax_amount","first","last","full","zipcode","display_name","unit_price","qty","item_image_url","item_url","categories","getCategories","line","discount_amount","discount_display_name","DISCOUNTED_AMOUNT","categoryTree","category","AFFIRM_SCRIPTS","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","h","k","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","insertBefore","public_api_key","script","_afterpayScriptLoader","_mapCurrencyToISO2","_afterpaySdk","_loadPaymentMethod","_redirectToAfterpay","redirect","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","_getScriptURI","isAfterpayWindow","AfterPay","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","toUpperCase","redirect_url","_getAmazonPayButton","click","isModalFlow","clone","cloneNode","replaceChild","_showLoadingSpinner","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","min","BRAINTREE_FASTLANE","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","HostedFieldType","isHostedCardFieldOptionsMap","CardNumber","isHostedStoredCardFieldOptionsMap","CardCodeVerification","CardNumberVerification","_blueSnapDirectHostedForm","_blueSnapDirect3ds","creditCard","is3dsEnabled","_paymentFieldsToken","_shouldUseHostedFields","form","_getPaymentFieldsToken","pfToken","_getBlueSnapDirectThreeDSecureData","bluesnapSubmitedForm","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapHostedFieldType","CardExpiry","CardName","CardCode","CREDIT_CARD_ERRORS","fieldType","invalid","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onEnter","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","kebabCase","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","_errors","_updateErrors","errorData","_style","_create","_getInput","_handleFocus","_handleBlur","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","fontWeight","styleKeys","_configureInput","autocomplete","inputMode","margin","outline","BlueSnapDirectSdkEnv","PRODUCTION","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","PaymentStatusTypes","orderRequest","_initializeOptions","frame","_createIframe","ACKNOWLEDGE","FINALIZE","bluesnapv2","storage","saveExtraItemsData","getStorageKey","readExtraItemsData","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","success","transaction","reference","configure","boltTransaction","validateTokenizeResultOrThrow","tokenizeResult","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","getTransactionReference","transactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","Number","isNaN","isAnalyticsEnabled","isUsBankAccountInstrumentLike","braintreeach","getMandateText","handleBraintreeError","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","submitPaymentPayload","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","_createElements","closeElement","mainElement","_element","_closeElement","_mainElement","_registerClick","opacity","_unregisterClick","_removeAfterTransition","classLayout","classClose","classOverlayText","background","transitionDuration","hasCloseButton","innerHtml","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","handleTransition","propertyName","DEFAULT_STYLES","ROTATION_ANIMATION","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","hide","handleTransitionEnd","bottom","left","position","right","top","transition","setStyleAttribute","transformStyle","animation","attrs","setProperty","head","sheet","CSSStyleSheet","insertRule","LOADING_INDICATOR_STYLES","loadingIndicator","braintreeOptions","bannerContainerId","loadPaypalCheckoutInstance","shouldHandleInstrumentDeclinedError","isProviderError","braintreeTokenizePayload","vaultPaymentInstrument","enableCheckoutPaywallBanner","renderPayPalMessages","onPaymentError","onRenderButton","loadingIndicatorContainer","toggleLoadingIndicator","tokenizePaymentOrThrow","onCancel","Messages","layout","logo","isBraintreePaypalProviderError","provider_error","isLPMsUpdateExperimentEnabled","braintreelocalmethods","isNonInstantPaymentMethod","executeWithNotInstantLPM","executeWithInstantLPM","getLPMsBasicPaymentData","basicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isBraintreeAcceleratedCheckoutCustomer","paypalFastlaneStyleSettings","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","preparePaymentPayload","braintreeCardComponent","cardComponentOptions","cardholderName","prefill","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","paypal_fastlane_token","mapToPayPalAddress","braintreePaymentProviderCustomer","paypalFastlaneSessionId","profile","showCardSelector","selectionChanged","selectedCard","braintreeFastlaneCustomer","selectedInstruments","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","formOptions","_hostedForm","isHostedFormEnabled","AdditionalActionType","_processResponse","additionalActionRequired","OffsiteRedirect","_performRedirect","_createFormattedPayload","fawryPaymentData","customerMobile","isThreeDSecureRequiredError","_handleThreeDSecure","payer_auth_request","callback_url","merchant_data","PaReq","TermUrl","MD","DOCUMENT_SUPPORTED_APMS","ccDocument","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","_getScriptUrl","_cardinalClient","prepare","_getClientToken","hostedForm","runBinProcess","getThreeDSecureData","_getOrderData","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalSignatureValidationErrors","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Yes","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","transactionId","consumer","BillingAddress","_mapToCardinalAddress","Account","_mapToCardinalAccount","Email1","ShippingAddress","Consumer","OrderDetails","OrderNumber","Amount","CurrencyCode","OrderChannel","TransactionId","AccountNumber","ExpirationMonth","ExpirationYear","NameOnAccount","cardinalAddress","FirstName","LastName","Address1","City","State","PostalCode","CountryCode","Address2","Phone1","Cardinal","_threeDSecureFlow","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","AuthenticationSourceStatus","digitalRiverScriptLoader","digitalRiverInitializeOptions","digitalriver","publicKey","getDigitalRiverInitializeOptions","digitalRiverJS","unsubscribe","loadWidget","digitalRiverCheckoutData","submitVaultedInstrument","isAuthenticateSourceAction","authenticateSource","loadSuccessResponse","readyForStorage","getDigitalRiverJs","onSuccessResponse","submitFormEvent","browserInfo","owner","reusable","billingAddressPayPal","onReadyResponse","paymentMethodConfiguration","mountComplianceSection","sellingEntity","onSubmitForm","disabledPaymentMethods","digitalRiverConfiguration","showSavePaymentAgreement","onReady","descriptiveError","digitalRiverDropComponent","createDropin","sourceId","source_id","sourceClientSecret","source_client_secret","authenticateSourceResponse","failed","authentication_not_required","confirm","complianceDiv","complianceOptions","classes","base","compliance","entity","drfooter","cssText","classList","add","stylesheetLoader","DigitalRiver","_isAdditionalActionRequired","redirectUrl","isAdditionalActionRequiredErrorResponse","googlePayToken","walletButton","extraData","_clickListener","ConfirmOrderStatus","_paypalCommerceScriptLoader","getOrderId","confirmOrderData","tokenizationData","cardNetwork","cardDetails","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","Approved","requestData","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","supportedCountries","supportedCountriesRequiringStates","klarnaScriptLoader","klarnaCredit","authorize","authorizationToken","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","klarnaWindow","Credit","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnaOrderInitialization","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","Payments","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","mollieScriptLoader","mollie","controllers","each","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","loadMollieJs","mollieClient","mountElements","disableButton","loadPaymentMethodsAllowed","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","isHostedPaymentFormEnabled","CREDIT_CARD","isHostedFieldAvailable","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","mollieHostWindow","isMollieWindow","Mollie","monerisOptions","profileId","createIframe","windowEventListener","instrumentSettings","frameref","monerisURL","handleMonerisResponse","definedFields","monerisQueryParams","pmmsg","display_labels","enable_exp","enable_cvd","css_body","cssBody","css_textbox","cssTextbox","css_textbox_pan","cssTextboxCardNumber","css_textbox_exp","cssTextboxExpiryDate","css_textbox_cvd","cssTextboxCVV","css_input_label","cssInputLabel","pan_label","creditCardLabel","exp_label","expiryDateLabel","cvd_label","cvdLabel","queryString","monerisResponse","responseCode","errorMessage","dataKey","orderPayload","_shouldSubmitFullPayload","shouldRenderPayPalButtonOnInitialization","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","handleClick","handleApprove","fieldsValues","getFieldsValues","isPaypalCommerceProviderError","messagesStyles","ratio","paypalOptions","paypalBNPLConfiguration","bannerConfiguration","renderMessages","onValidationPassed","paypalMessagesOptions","paypalcommercealternativemethods","shouldRenderFields","renderFields","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","fieldsOptions","PaymentFields","isCreditCardFormFields","isCreditCardVaultedFormFields","CardExpiryVerification","isPayPalCommerceAcceleratedCheckoutCustomer","paypalcommercecreditcards","onCreditCardFieldsRenderingError","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","liabilityShift","No","Unknown","inputEvents","onChangeHandler","onFocusHandler","onBlurHandler","onInputSubmitRequest","CardFields","cardFields","stylizeInputContainers","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","getCardFieldsOrThrow","CVVField","ExpiryField","NameField","NumberField","cardExpiryVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","fieldsErrors","getInvalidErrorByFieldType","validationErrors","commonStyles","marginBottom","marginLeft","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","payPalFastlaneSdk","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","paypalcommerceratepay","legalTextContainer","loadingContainerId","createFraudNetScript","loadFraudnetConfig","renderLegalText","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","national_number","initializePollingMechanism","fraudNetScript","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","getDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","useMetadata","orderStatus","isOrderApproved","PollingStop","isPollingError","PollingError","isPayPalFastlaneCustomer","paypalFastlaneStyling","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","isVaultedFlow","paypalFastlaneCustomer","paypalComponentMethods","getPayPalComponentMethodsOrThrow","selectedInstrument","threeDSecureFlow","_isThreeDSTwoExperimentOn","newPaymentData","SquareIntent","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","isCompletelyValid","distinctUntilChanged","_mapToSquareBillingContact","STORE","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","_shouldVerify","cardTokenizationResult","tokenData","tokenForSavingCard","store_card_nonce","store_card_token","_getSquareCardIdOrThrow","verificationToken","three_d_secure","SquareV2WebPaymentsSdkEnv","LIVE","isSquareV2Window","assertSquareV2Window","Square","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","StripeV3ErrorType","AuthFailure","APM_REDIRECT","Alipay","stripev3","isDeinitialize","useIndividualCardFields","stripeV3Client","mountCardVerificationFields","mountCardFields","stripeElement","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isCancellationError","isAuthError","getStripeJs","confirmAlipayPayment","return_url","handleActions","mapStripePaymentData","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","billingDetails","mapStripeBillingDetails","createPaymentMethod","billing_details","stripeCardElements","mapStripeAddress","zipCodeElementOptions","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","isAdditionalActionError","needsConfirm","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","_mapStripeAddress","IF_REQUIRED","confirmParams","payment_method_data","isRedirectAction","isOnPageAdditionalAction","bg","cs","da","el","et","fi","fil","he","hu","ja","ko","lt","lv","mt","nb","ro","ru","sk","sl","th","tr","vi","SOFORT","EPS","GRABPAY","BANCONTACT","GIROPAY","ALIPAY","KLARNA","stripeUPEIntegrationService","_loadStripeElement","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_executeWithAPM","_executeWithoutRedirect","_getPaymentPayload","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","_loadStripeJs","_isStripeElementUpdateEnabled","NEVER","AUTO","wallets","applePay","googlePay","_getStripeElementTerms","_updateStripeLinkStateByElementType","_updateStripeElement","_confirmStripePaymentOrThrow","stripePaymentData","confirmPayment","confirmationResult","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","Link","stripeScriptLoader","stripeSVGSizeCoefficient","_initializeStripeElement","paymentMethodSelect","handleClosePaymentMethod","_getElementAppearance","fonts","cssSrc","defaultCollapsed","radios","spacedAccordionItems","visibleAccordionItemsCount","_onStripeElementChange","_collapseStripeElement","titleFontSize","titleFontWeight","titleColor","radioFocusColor","radioIconOuterWidth","radioIconOuterStrokeWidth","radioIconInnerWidth","radioIconSize","_getRadioIconSizes","borderBottomWidth","outerWidth","strokeWidth","outerStrokeWidth","stroke","innerRadius","fill","realOuterWidth","realOuterStrokeWidth","realInnerWidth","percentageCoefficient","innerWidth","stripeEqualOuterWidth","stripeEqualOuterStrokeWidth","stripeEqualInnerRadius","collapse","payment_method_id","selectedMethodId","isStripePaymentEvent","collapsed","FieldType","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","loadTDOnlineMartJs","tdOnlineMartClient","mountHostedFields","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","commonPaymentData","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isCreateTokenError","tdOnlineMartWindow","customcheckout","PAYMENT_CANNOT_CONTINUE","worldpay","_submitAdditionalAction","iframeHidden","_isValidJsonWithSessionId","SessionId","onLoadError","_createHiddenIframe","formId","inputBin","inputJWT","userAgent","match","srcdoc","outerHTML","str","saveExternalId","externalId","storefrontPaymentRequestSender","_prepareForReferredRegistration","CountryActionType","_countryRequestSender","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","createPaymentStrategyRegistry","paymentStrategyFactories","createPaymentStrategy","PaymentStrategyType","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","_namespace","isPPSDKPaymentMethod","initializationStrategy","PPSDK","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","_isInitializedHostedForm","_formOptions","_mapFieldType","_mapErrors","_handleCardTypeChange","cards","_handleInputSubmitRequest","_handleValidityChange","_isValidForm","_mapValidationErrors","StoredCardVerification","_mapFieldOptions","_mapStyleOptions","_cardFields","braintreeHostedFormState","_mapBillingAddress","tokenizationPayload","_mapTokenizeError","tokenizeForStoredCardVerification","countryName","internalLabel","expirationDate","cvv","mapStyles","_isValidParam","isPotentiallyValid","fieldKey","_createInvalidError","isStoredCard","cvvValidation","_createRequiredError","expirationDateValidation","cardNumberValidation","cardNameValidation","formErrorDataKey","_braintreeHostedForm","_threeDSecureOptions","preloadPaypalCheckout","tokenizeCard","_getErrorsRequiredFields","_mapToCreditCard","creditCards","challenge3DSVerification","appendSessionId","processedPayment","initializeHostedForm","validateHostedForm","isInitializedHostedForm","deinitializeHostedForm","tokenizeHostedForm","tokenizeHostedFormForStoredCardVerification","verifyCardWithHostedForm","_present3DSChallenge","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","verification","roundedAmount","collectDeviceData","endpoint","_braintreePaymentProcessor","_braintreeIntegrationService","_isHostedFormInitialized","_is3dsEnabled","_deviceSessionId","_shouldInitializeBraintreeFastlane","_initializeBraintreeFastlaneOrThrow","_prepareHostedPaymentData","_preparePaymentData","_isSubmittingWithStoredCard","_shouldPerform3DSVerification","storedCreditCardNonce","_initializeBraintreeVenmo","_braintreeVenmoCheckout","_formattedPayload","_braintreeVenmoTokenize","_paymentStrategyActionCreator","visaInitOptions","isCreditCardLike","_CBAMGPSScriptLoader","_sessionId","isTestModeFlagEnabled","_threeDSjs","isConfigured","wsVersion","storeId","_initiateAuthentication","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","_authenticatePayer","attempt","authenticatePayer","cause","fullScreenRedirect","ThreeDS","_masterpassClient","_walletButton","_createMasterpassPayload","ActionTypes","isOpyPaymentMethod","widgetConfig","OpyErrorType","InvalidCart","_storefrontPaymentRequestSender","opy","_installWidget","nextAction","FORM_POST","formPost","formPostUrl","formFields","fieldName","fieldValue","append","decodeURI","widgetContainer","loadOpyWidget","Config","OpyRegion","AU_REGION_URL","SOURCES","AU","UK","US","OpenpayWidgets","_useRedirectFlow","paypalexpress","useRedirectFlow","_isInContextEnabled","_paypalSdk","closeFlow","_isAcknowledgedOrFinalized","initXO","startFlow","SubStrategyType","PENDING_REDIRECT_PARAM","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","stringifyUrl","exclude","isAnyContinue","overSome","x","isString","isUndefined","availableMethods","_humanVerificationHandler","form_fields","redirectionState","RedirectionState","handleRedirect","humanVerificationHandler","available_methods","handleHumanVerification","humanVerification","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","createStepHandler","StepHandler","ContinueHandler","COMPLETED_PAYMENTS_KEY","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","_subStrategyRegistry","_paymentResumer","_completedPayments","PPSDKCompletedPayments","subStrategy","resume","getPPSDKMethod","_subStrategy","getToken","cond","constant","CARD","NONE","stubTrue","UNSUPPORTED","_ppsdkStepHandler","humanVerificationCallback","_stepHandler","createSubStrategyRegistry","stepHandler","SubStrategyRegistry","CardSubStrategy","NoneSubStrategy","auth_token","_wepayRiskClient","getRiskToken","payloadWithToken","_riskClient","WePay","risk","generate_risk_token","get_risk_token","InstrumentActionType","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","session","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","valueOf","isFuture","vaultAccessExpiry","newDate","getTime","setMinutes","getMinutes","getVaultAccessToken","isTransactional","transformResponse","vaultedInstruments","_transformVaultedInstruments","vaulted_instruments","transformErrorResponse","transformVaultAccessResponse","expires_at","_isPayPalInstrument","default_instrument","external_id","trusted_shipping_address","mapToPayPalInstrument","_isBankInstrument","mapToBankInstrument","last_4","untrusted_shipping_address_card_verification_mode","mapToCardInstrument","method_type","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionType","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","getConsignmentById","consignmentLineItems","cartItems","searchArea","ShippingStrategyActionType","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","showShippingAddressSelector","selectedAddress","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","_paypalCommerceSdk","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","_stripeUPEScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionType","sendSignInEmail","emailRequest","SendSignInEmailRequested","SendSignInEmailSucceeded","SendSignInEmailFailed","_messageCustomizer","_extensionEventBroadcaster","_countryActionCreator","_couponActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","isDevelopment","_errorTransformer","isCheckoutServiceError","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","handleExtensionCommand","handler","CheckoutService","withMemoizedCombiner","creator","combiner","pop","combinerArgs","createSelectorCreator","defaultMemoize","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","currentValue","newValue","objectSet","DEFAULT_STATE","statuses","billingAddressReducer","combineReducers","dataReducer","composeReducers","errorsReducer","statusesReducer","reducer","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","objectMerge","currentObject","newObject","CheckoutButtonActionType","cartReducer","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","configReducer","couponReducer","giftCertificateReducer","customerReducer","customerStrategyReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extensionReducer","formFieldsReducer","countryReducer","orderReducer","metaReducer","orderBillingAddressReducer","paymentReducer","paymentMethodReducer","array","defaultPredicate","derivedPredicate","findIndex","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","paymentStrategyReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","paymentProviderCustomerReducer","instrumentReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remoteCheckoutReducer","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","objectFlatten","parent","flattened","keyString","objectWithSortedKeys","sortedArray","current","pickupOptionReducer","sortedflattenedMeta","shippingCountryReducer","shippingStrategyReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signInEmailReducer","storeCreditReducer","subscriptionsReducer","checkoutReducer","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","deepFreeze","trap","createProxy","barclays","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","moneris","cba_mpgs","worldpayaccess","tdonlinemart","normalize","createInternalCheckoutSelectorsFactory","getUpdateError","getContinueAsGuestError","getLoadError","isContinuingAsGuest","getInitializeError","getDeinitializeError","getCoupons","getRemoveError","getApplyError","isApplying","isRemoving","getCreateAccountError","isCreatingCustomerAccount","getCreateAddressError","isCreatingCustomerAddress","getOrderBillingAddress","getInternalPayment","getGatewayPayment","getHostedPayment","isPaymentDataSubmitted","getEmail","getSendError","isSending","createBillingAddressSelector","continueAsGuestError","loadError","memoizeOne","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","removeCouponError","applyCouponError","isApplyingCoupon","isRemovingCoupon","createCustomerSelector","isCreating","createAddressError","isCreatingAddress","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","isMatch","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createRemoteCheckoutSelector","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createPaymentSelector","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","signInEmail","sendError","createExtensionSelector","createExtensionSelectorFactory","checkoutButton","orderBillingAddress","remoteCheckout","shippingCountries","selectors","shouldWarnMutation","createCheckoutStore","initialState","requestErrorFactory","actionTransformer","action$","createInternalCheckoutSelectors","createCheckoutService","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","getSelectShippingOptionError","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","createCheckoutStoreSelector","createCheckoutStoreErrorSelector","createCheckoutStoreStatusSelector","checkoutVariantIdentificationToken","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","customerRegistryV2","extensionActionCreator","ExtensionActionCreator","ExtensionRequestSender","extensionMessenger","ExtensionMessenger","storeProjection","val","checkoutUserExperienceSettings","getLoadCheckoutError","getUpdateCheckoutError","getSubmitOrderError","getFinalizeOrderError","getLoadOrderError","getLoadCartError","getLoadBillingCountriesError","getLoadShippingCountriesError","getLoadPaymentMethodsError","getLoadPaymentMethodError","getInitializePaymentError","getInitializeCustomerError","getUpdateBillingAddressError","getUpdateSubscriptionsError","getUpdateShippingAddressError","getDeleteConsignmentError","getUpdateConsignmentError","getCreateConsignmentsError","getInitializeShippingError","getApplyStoreCreditError","getApplyCouponError","getRemoveCouponError","getApplyGiftCertificateError","getRemoveGiftCertificateError","getLoadInstrumentsError","getDeleteInstrumentError","getLoadConfigError","getSignInEmailError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingPickupOptions","messenger","subscribers","ExtensionEventBroadcaster","createExtensionEventBroadcaster","remoteCheckoutRequestSender","paymentRequestTransformer","paymentRequestSender","braintreePaymentProcessor","braintreeHostedForm","createBraintreePaymentProcessor","paymentStrategyActionCreator","BARCLAYS","BRAINTREE_VISA_CHECKOUT","CBA_MPGS","CONVERGE","BNZ","MASTERPASS","OPY","PAYPAL_EXPRESS","PAYPAL_EXPRESS_CREDIT","PPSDKStrategy","PaymentResumer","WE_PAY","consignmentRequestSender","createShippingStrategyRegistry","isTerminalCacheKeyMap","_lastId","_map","maps","_usedMaps","maxSize","onExpire","getKey","_resolveMap","parentMap","usedCount","_generateMap","_removeLeastUsedMap","getUsedCount","isMatched","mapIndex","unshift","terminalMap","recentlyUsedMap","_removeMap","isRootCacheKeyMap","selectorDecorator","resolver","memoizedMethod","cachedValue","isPrivate","selectorMethodDecorator","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","CheckoutButtonErrorSelector","isInitializingButton","isDeinitializingButton","CheckoutButtonStatusSelector","createCheckoutButtonSelectors","_buttonStrategyActionCreator","_state","initializeButton","containerIds","idPrefix","containers","uniqueId","setUniqueElementId","deinitializeButton","CheckoutButtonInitializer","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","fundingicons","tagline","messagingContainerId","_renderPayPalComponents","_renderPayPalMessages","_renderPayPalButton","shouldProcessPayment","onAuthorizeError","onEligibilityFailure","validButtonStyle","_setupPayment","_tokenizePayment","_removeElement","isMessageContainerAvailable","_createBuyNowCart","_buyNowCart","buyNowCartId","CheckoutButtonNotInitialized","_paypalScriptLoader","_host","fundingCreditOption","allowedSources","allowCredit","disallowedSources","Button","funding","allowed","disallowed","RECT","RESPONSIVE","onAuthorize","paymentID","payerID","payerId","payerInfo","payer_info","isWithBuyNowFeatures","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","payloadJSON","buyNowCart","amazonPayV2RequestSender","ButtonStyleOption","_requiresShipping","defaultStyle","backgroundPosition","backgroundRepeat","backgroundSize","cursor","minHeight","minWidth","White","backgroundImage","WhiteBorder","Black","getApplePayButtonStyle","_getRequestWithEmptyTotal","onpaymentmethodselected","_handlePaymentMethodSelected","completePaymentMethodSelection","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","domainUrl","buttonHeight","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","paymentSuccess","toVisaCheckoutAddress","alignItems","getVenmoButtonStyle","WHITE","BLUE","braintreevenmo","cartButtonStyles","renderVenmoButton","handleInitializationVenmoError","removeVenmoContainer","venmoButton","buyBowCart","removeAttribute","handlePostForm","_getMethodOrThrow","_countryCode","_getBuyNowTransactionInfo","_getTransactionInfo","buyNowFlowCallbacks","messagingContainer","paypalMessagesSdk","getValidVenmoButtonStyles","gold","paypalExpressScriptLoader","loadPaypalSDK","paypalSDK","getStyle","getPaymentData","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","braintreeSdkCreator","BRAINTREE_PAYPAL_CREDIT","PAYPALEXPRESS","createCheckoutButtonRegistry","EmbeddedCheckoutEventType","NotEmbeddableErrorType","UnknownError","EmbeddedContentEventType","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","_iframeCreator","_messageListener","_messagePoster","_loadingIndicator","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","encodeURIComponent","lastAttempt","MissingContent","EmbeddedCheckout","MissingContainer","allowPaymentRequest","allow","contentId","STORAGE_PREFIX","embedCheckout","handleFrameLoadedEvent","hasAttribute","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","IframeEmbeddedCheckoutMessenger","NoopEmbeddedCheckoutMessenger","createEmbeddedCheckoutMessenger","parentWindow","DEFAULT_LOCALE","KEY_PREFIX","_logger","_transformConfig","locales","_locales","_translations","_formatters","_isCspNonceExperimentEnabled","isCspNonceExperimentEnabled","mapKeys","translationKey","_hasTranslations","translate","prefixedKey","IntlMessageFormat","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","messageFormat","compile","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","union","fallbackLocale","parentKey","resultKey","LanguageService","createLanguageService","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","checkoutService","analytics","checkoutSteps","_checkoutStarted","_completedSteps","_viewedSteps","_analyticStepOrder","trackCheckoutStarted","extraItemsData","track","getTrackingPayload","revenue","trackOrderComplete","isMissingOrdersExperimentEnabled","affiliation","products","product","trackStepViewed","stepId","getIdFromStep","hasStepViewed","trackViewed","backfill","trackStepCompleted","hasStepCompleted","trackCompleted","shippingMethod","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","physicalAndDigitalItems","itemAttributes","image_url","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","_selectedPaymentMethodId","customerPaymentMethodExecuted","_shouldTrackFastlaneEvent","_trackEmailSubmitted","paymentComplete","_trackOrderPlaced","selectedPaymentMethod","_trackApmSelected","walletButtonClick","isAnalyticEnabled","isBraintreeAnalyticsV2Enabled","isAvailableAnalyticEventsMethods","events","_getBraintreeEventsOrThrow","emailSubmitted","_getEmailSubmittedEventOptions","isWalletButton","apmSelected","_getApmSelectedEventOptions","orderPlaced","_getOrderPlacedEventOptions","_getEventCommonOptions","isGuestCustomer","experiments","treatment_group","context_type","context_id","page_type","page_name","partner_name","user_type","store_id","merchant_name","experiment","apmList","user_email_saved","apm_shown","apm_list","apm_selected","apm_location","selected_payment_method","currency_code","createBraintreeAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","createStoredCardHostedFormService","AnalyticStepType","AnalyticStepOrder","bodlEvents","_emailEntryBegan","_shippingOptionsShown","setState","checkoutBegin","_getCommonCheckoutData","emitCheckoutBeginEvent","orderPurchased","emitOrderPurchasedEvent","event_id","channel_id","cart_value","coupon_codes","shipping_cost","line_items","_getProducts","stepCompleted","currentStep","_hasStepCompleted","_trackCompletedStep","customerEmailEntry","emit","customerSuggestionInit","customerSuggestionExecute","showShippingMethods","paymentOption","commonData","emitPaymentDetailsProvidedEvent","clickPayButton","paymentRejected","exitCheckout","_trackShippingStepCompleted","emitShippingDetailsProvidedEvent","base_price","sale_price","purchase_price","product_name","gift_certificate_id","gift_certificate_name","gift_certificate_theme","theme","variant_id","coupon_amount","couponAmount","brand_name","category_names","flatten","retail_price","retailPrice","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"checkout-sdk.js","mappings":"kCAAAA,EAAOC,QAAUC,QAAQ,iB,UCAzBF,EAAOC,QAAUC,QAAQ,gD,GCCrBC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaL,QAGrB,IAAID,EAASG,EAAyBE,GAAY,CAGjDJ,QAAS,CAAC,GAOX,OAHAO,EAAoBH,GAAUL,EAAQA,EAAOC,QAASG,GAG/CJ,EAAOC,OACf,CCrBAG,EAAoBK,EAAKT,IACxB,IAAIU,EAASV,GAAUA,EAAOW,WAC7B,IAAOX,EAAiB,QACxB,IAAM,EAEP,OADAI,EAAoBQ,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,CAAM,ECLdN,EAAoBQ,EAAI,CAACX,EAASa,KACjC,IAAI,IAAIC,KAAOD,EACXV,EAAoBY,EAAEF,EAAYC,KAASX,EAAoBY,EAAEf,EAASc,IAC5EE,OAAOC,eAAejB,EAASc,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDX,EAAoBY,EAAI,CAACK,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFlB,EA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ACrC/5F,EACAk1F,EACArrE,EACAU,GAEEt3C,GAAa,KAAAyC,oBACb69F,EAAc7B,GAAkBz+F,EAAYi3C,GAC5CN,EAAoB,IAAI,GAAkBriE,GAC1Cq9G,EAAiC,IAAI,GAA+B33E,GAkL1E,OAhLA+S,EAASnuC,SACL,GAAoBmoI,UACpB,WACI,WAAI,GACAzyI,EACAsiE,EACAI,EACAL,EACA,IAAI,GACAriE,EACA0iE,EACA,IAAI,GAAe,IAAI,GAAqBtuD,KARpD,IAaRqkC,EAASnuC,SACL,GAAoBmT,WACpB,WACI,WAAI,GACAzd,EACAsiE,EACAI,EACAD,EACA4vE,EACA,IAAI,GACA,IAAI,IAAsB,IAAAz9H,mBAAmBN,QAC7CA,QARR,IAaRmkC,EAASnuC,SACL,GAAoB+sD,iBACpB,WACI,WAAI,GACAr3D,EACAsiE,EACAI,EACAD,EACA4vE,EALJ,IASR55F,EAASnuC,SACL,GAAoBooI,yBACpB,WACI,WAAI,GACA1yI,EACAmiE,EACAM,EACA+vE,EACA9vE,EACAJ,EACAsC,GAA4CxwD,EAAcsxB,GAC1D,IAAI,GAAyBtxB,GARjC,IAYRqkC,EAASnuC,SACL,GAAoBqoI,UACpB,WACI,WAAI,GACA3yI,EACAsiE,EACAI,EACAL,EACAI,EACA,IAAI,GAAoBruD,GACxBmjB,EAPJ,IAWRkhB,EAASnuC,SACL,GAAoBsoI,UACpB,WACI,WAAI,GACA5yI,EACAsiE,EACAI,EACAL,EACA32C,EALJ,IASR+sB,EAASnuC,SACL,GAAoBuoI,KACpB,WACI,WAAI,GACA7yI,EACAsiE,EACAI,EACAL,EACA,IAAI,GACAriE,EACA0iE,EACA,IAAI,GAAe,IAAI,GAAqBtuD,KARpD,IAaRqkC,EAASnuC,SACL,GAAoBwoI,YACpB,WACI,WAAI,GACA9yI,EACAsiE,EACAI,EACA,IAAI,GAAuBtuD,GAC3BmjB,EALJ,IASRkhB,EAASnuC,SACL,GAAoByoI,KACpB,WACI,WAAI,GACA/y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BA,CAC3B,CDoBQg5I,CAAch5I,QACP,IAAI,GAAmB7P,EAAW6P,OAAO81I,WAAWjqJ,UAGxD,IAAI,EACf,C","sources":["webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/compat get default export","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/webpack/runtime/make namespace object","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/request-sender\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/script-loader\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/data-store\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"lodash\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs/operators\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/create-data-store-projection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/get-environment.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/console-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/noop-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/get-default-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/create-logger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/memoize\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cachable-action-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/is-action-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cache-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/errors/checkout-not-available-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-default-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-params.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/is-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/resolve-id-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/getShippableItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/getLineItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/util-types/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/isInternalCheckoutSelectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/amazon-pay-v2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/create-amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/to-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-scripts-integrity.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-sdk-verison.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/form-poster\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@braintree/browser-detection\"","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/paypal.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/braintree-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/checkout-buttons/default-checkout-button-height.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-credit/create-braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"local-storage-fallback\"","webpack://@bigcommerce/checkout-sdk/./packages/storage/src/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/create-braintree-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/utility/src/bind-decorator/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/currency-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/shipping/items-require-shipping.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-card-network-key.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-error-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-initialize-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-key.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-additional-action-processable.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/create-google-pay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-adyenv2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-adyenv3-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-authorizenet-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-authorizenet-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-authorizenet-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/is-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-checkoutcom-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-checkoutcom-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-threedsecure-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-checkoutcom-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-cybersource-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-cybersource-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-bnz-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-orbital-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-orbital-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-initialization-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/google-pay-stripe-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-stripe-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripeupe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-worldpayaccess-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-worldpayaccess-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-braintree-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-braintree-token-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-braintree-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-paypal-commerce-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-tdonlinemart-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/guards/is-google-pay-td-online-mart-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/customer/create-google-pay-tdonlinemart-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/create-paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/create-paypal-commerce-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/paypal-commerce-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/create-paypal-commerce-fastlane-utils.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/get-fastlane-styles.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/paypal-commerce-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/create-paypal-commerce-fastlane-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-upe-payment-method-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-or-merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/apple-pay/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-comparator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-changed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/is-iframe-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/payment-human-verification-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/create-spam-protection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-payment-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-value-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/hosted-input-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-order-data-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-tax-provider-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/bigpay-client\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/map-to-internal-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-coupon.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-gift-certificate.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/generated/checkout-button-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-items.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-gift-certificate-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-cart.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/promotion/map-to-discount-notifications.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/map-to-internal-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-expiry-formatter.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"card-validator\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-number-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/map-to-internal-order.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/map-to-internal-shipping-option.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-actions-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-widget-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/errors/update-subscriptions-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-plain-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/clone-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/default-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/payment-integration-store-projection-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-sdk-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/visacheckout-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-visacheckout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/get-callback-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/masterpass/masterpass-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/square/square-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-internal-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-commands.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/unsupported-extension-command-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-event-broadcaster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/subscribers/subscribe-consignments-change.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-card-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-account-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/create-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-boleto-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/create-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirm-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/affirmJs.ts","webpack://@bigcommerce/checkout-sdk/./packages/affirm-integration/src/create-affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/afterpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/is-afterpay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/afterpay-integration/src/create-afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-utils/src/isAmazonPayAdditionalActionError.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-3ds.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-hosted-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-hosted-stored-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-input-validation-error-description.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-hosted-input-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-name-on-card-input.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-array-of-allowed-props.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/bluesnap-direct-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card/create-bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm/bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-provider-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/utils/is-bluesnap-direct-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm/create-bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnapv2/bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnapv2/create-bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/analytics-extra-items-manager.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/is-analytics-step-tracker-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-with-account-creation.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/is-bolt-payment-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-us-bank-account-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-ach/braintree-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-ach/create-braintree-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/create-braintree-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-paypal-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/create-braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/braintree-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-fastlane/create-braintree-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-custom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/create-checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/isThreeDSecureRequiredError.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/create-checkoutcom-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-sepa/create-checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-ideal/checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-ideal/create-checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-apm/checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/checkoutcom-custom-integration/src/checkoutcom-apm/create-checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/clearpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/clearpay-integration/src/create-clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/create-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-three-d-secure-flow.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersource/cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersource/create-cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cardinal-integration/src/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-credit-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersourcev2/cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/cybersource-integration/src/cybersourcev2/create-cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/digitalriver-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/digitalriver-integration/src/create-digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/create-external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-utils/src/utils/is-additional-action-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-adyenv2-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/gateways/google-pay-adyenv3-gateway.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-authorizenet-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-checkoutcom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-orbital-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-braintree-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/google-pay-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/payment/create-google-pay-tdonlinemart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-execute-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/humm-integration/src/humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/humm-integration/src/create-humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarna-supported-countries.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/klarna-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarna/create-klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/klarnav2-token-updater.ts","webpack://@bigcommerce/checkout-sdk/./packages/klarna-integration/src/klarnav2/create-klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/create-legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/mollie-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/is-mollie-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/mollie-integration/src/create-mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/moneris-integration/src/moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/moneris-integration/src/create-moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/no-payment-data-required-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/create-no-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/create-offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/create-offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-commerce-provider-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/get-paypal-messages-styles-from-bnpl-config.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-vaulted-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-commerce-accelerated-checkout-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/create-paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-ratepay/paypal-commerce-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-ratepay/create-paypal-commerce-ratepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-utils/src/utils/is-paypal-fastlane-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/paypal-commerce-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-fastlane/create-paypal-commerce-fastlane-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-pro-integration/src/paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-pro-integration/src/create-paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sagepay-integration/src/sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sagepay-integration/src/create-sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/create-sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/enums.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/is-squarev2-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/create-squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/is-individual-card-element-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/stripev3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripev3/create-stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/is-stripe-payment-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/stripe-integration/src/stripe-upe/create-stripe-ocs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/isTdOnlineMartAdditionalAction.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/is-create-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/td-online-mart-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/td-bank-integration/src/create-td-online-mart-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/worldpayaccess-integration/src/create-worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/storefront-payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/zip-integration/src/zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/zip-integration/src/create-zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/storage/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/barclays/barclays-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bnz/bnz-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-credit-card-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-credit-card-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-declined-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-library.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-express-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"query-string\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/RedirectionState.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/continue-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/redirect.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/human-verification/human-verification.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/success.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/failure.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/create-step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-completed-payments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/get-ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/card.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/none.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/card-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/none-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-risk-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-response-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-paypal-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-bank-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/amazon-pay-v2/amazon-pay-v2-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/braintree/braintree-fastlane-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/default/default-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/paypal-commerce/paypal-commerce-fastlane-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/stripe-upe/stripe-upe-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-message-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/to-single-line.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service-error-transformer.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"reselect\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/with-memoized-combiner.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-selector.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"shallowequal\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-shallow-equal-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unrecoverable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-internal-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-storefront-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/omit-deep.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/clear-error-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/array-replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-merge.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/merge-or-push.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-flatten.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-with-sorted-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/create-freeze-proxy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/supported-payment-instruments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/is-address-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-internal-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-provider-customer/payment-provider-customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/create-extension-event-broadcaster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-maps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-resolver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/selector-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-private.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/is-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/masterpass/masterpass-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/errors/amazon-pay-v2-config-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/isWithBuyNowFeatures.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/amazon-pay-v2-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/amazon-pay-integration/src/create-amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/braintree-visa-checkout-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-visa-checkout/create-braintree-visa-checkout-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/isUnsupportedBrowserError.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-venmo/create-braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-braintree-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-paypal-commerce/create-google-pay-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-adyenv2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-adyenv3-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-authorizenet-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-checkoutcom-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-cybersource-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-orbital-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/google-pay-stripe/create-google-pay-stripe-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-worldpayaccess-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/google-pay-integration/src/factories/button/create-google-pay-tdonlinemart-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/invalid-login-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/not-embeddable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/embedded-content-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embed-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/handle-frame-loaded-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/iframe-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/noop-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/create-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"intl-messageformat\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"messageformat\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/create-language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-tracker-ga.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/noop-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/create-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-utils/src/utils/is-braintree-fastlane-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/braintree-analytic-tracker/braintree-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/braintree-analytic-tracker/create-braintree-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/paypal-commerce-analytic-tracker/paypal-commerce-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/paypal-commerce-analytic-tracker/create-paypal-commerce-analytic-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/stored-card-hosted-form-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/create-hosted-form-stored-card-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/analytics-steps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/bodl-emitter-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/noop-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/create-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/is-bodl-enabled.ts"],"sourcesContent":["module.exports = require(\"iframe-resizer\");","module.exports = require(\"iframe-resizer/js/iframeResizer.contentWindow\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/request-sender\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/script-loader\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/data-store\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"lodash\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs/operators\");","import { Action, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, Observable, of, throwError } from 'rxjs';\n\nexport default function throwErrorAction(\n type: TType,\n error?: TPayload,\n meta?: TMeta,\n): Observable> {\n if (isErrorAction(error)) {\n return concat(of(error), throwError(createErrorAction(type, error.payload, meta)));\n }\n\n return throwError(createErrorAction(type, error, meta));\n}\n\nfunction isErrorAction(action: any): action is Action {\n return action && action.type && action.error;\n}\n","import { setPrototypeOf } from '../../utility';\n\nimport CustomError from './custom-error';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentProviderCustomer,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingPaymentProviderCustomer:\n return 'Unable to proceed because payment provider customer is unavailable.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum BillingAddressActionType {\n UpdateBillingAddressRequested = 'UPDATE_BILLING_ADDRESS_REQUESTED',\n UpdateBillingAddressSucceeded = 'UPDATE_BILLING_ADDRESS_SUCCEEDED',\n UpdateBillingAddressFailed = 'UPDATE_BILLING_ADDRESS_FAILED',\n\n ContinueAsGuestRequested = 'CONTINUE_AS_GUEST_REQUESTED',\n ContinueAsGuestSucceeded = 'CONTINUE_AS_GUEST_SUCCEEDED',\n ContinueAsGuestFailed = 'CONTINUE_AS_GUEST_FAILED',\n}\n\nexport type BillingAddressAction = ContinueAsGuestAction | UpdateBillingAddressAction;\n\nexport type UpdateBillingAddressAction =\n | UpdateBillingAddressRequested\n | UpdateBillingAddressSucceeded\n | UpdateBillingAddressFailed;\n\nexport type ContinueAsGuestAction =\n | ContinueAsGuestRequested\n | ContinueAsGuestSucceeded\n | ContinueAsGuestFailed;\n\nexport interface UpdateBillingAddressRequested extends Action {\n type: BillingAddressActionType.UpdateBillingAddressRequested;\n}\n\nexport interface UpdateBillingAddressSucceeded extends Action {\n type: BillingAddressActionType.UpdateBillingAddressSucceeded;\n}\n\nexport interface UpdateBillingAddressFailed extends Action {\n type: BillingAddressActionType.UpdateBillingAddressFailed;\n}\n\nexport interface ContinueAsGuestRequested extends Action {\n type: BillingAddressActionType.ContinueAsGuestRequested;\n}\n\nexport interface ContinueAsGuestSucceeded extends Action {\n type: BillingAddressActionType.ContinueAsGuestSucceeded;\n}\n\nexport interface ContinueAsGuestFailed extends Action {\n type: BillingAddressActionType.ContinueAsGuestFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class UnableToContinueAsGuestError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to continue as a guest because the customer is already signed in.',\n );\n\n this.name = 'UnableToContinueAsGuestError';\n this.type = 'unable_to_continue_as_guest';\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Response } from '@bigcommerce/request-sender';\nimport { isEmpty } from 'lodash';\nimport { concat, defer, empty, merge, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { Checkout, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { GuestCredentials } from '../customer';\nimport { SubscriptionsActionCreator, UpdateSubscriptionsAction } from '../subscription';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\nimport {\n BillingAddressActionType,\n ContinueAsGuestAction,\n UpdateBillingAddressAction,\n} from './billing-address-actions';\nimport { UnableToContinueAsGuestError } from './errors';\n\nimport { BillingAddressRequestSender } from '.';\n\nexport default class BillingAddressActionCreator {\n constructor(\n private _requestSender: BillingAddressRequestSender,\n private _subscriptionActionCreator: SubscriptionsActionCreator,\n ) {}\n\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const isBillingFixExperimentEnabled =\n state.config.getConfig()?.storeConfig.checkoutSettings.features[\n 'CHECKOUT-8392.fix_billing_creation_in_checkout'\n ] ?? true;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const customer = state.customer.getCustomer();\n\n if (customer && !customer.isGuest) {\n throw new UnableToContinueAsGuestError();\n }\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n let billingAddressRequestBody: Partial;\n\n if (!billingAddress) {\n billingAddressRequestBody = credentials;\n } else {\n const { country, ...existingBillingAddressRequestBody } = billingAddress;\n\n billingAddressRequestBody = {\n ...existingBillingAddressRequestBody,\n ...credentials,\n };\n }\n\n const hasBillingAddress = !isEmpty(billingAddress);\n\n return merge(\n concat(\n of(createAction(BillingAddressActionType.ContinueAsGuestRequested)),\n defer(async () => {\n const { body } = await this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n isBillingFixExperimentEnabled,\n hasBillingAddress,\n options,\n );\n\n return createAction(\n BillingAddressActionType.ContinueAsGuestSucceeded,\n body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(BillingAddressActionType.ContinueAsGuestFailed, error),\n ),\n ),\n this._updateCustomerConsent(credentials, options),\n );\n };\n }\n\n updateAddress(\n address: Partial,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const isBillingFixExperimentEnabled =\n state.config.getConfig()?.storeConfig.checkoutSettings.features[\n 'CHECKOUT-8392.fix_billing_creation_in_checkout'\n ] ?? true;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(BillingAddressActionType.UpdateBillingAddressRequested));\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n const hasBillingAddress = !isEmpty(billingAddress);\n\n // If email is not present in the address provided by the client, then\n // fall back to the stored email as it could have been set separately\n // using a convenience method. We can't rely on billingAddress having\n // an ID to consider that there's a preexisting email, as billingAddress\n // object from Order doesn't have an ID.\n const billingAddressRequestBody = {\n ...address,\n email:\n typeof address.email === 'undefined' && billingAddress\n ? billingAddress.email\n : address.email,\n };\n\n if (billingAddress && billingAddress.id) {\n billingAddressRequestBody.id = billingAddress.id;\n }\n\n this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n isBillingFixExperimentEnabled,\n hasBillingAddress,\n options,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n BillingAddressActionType.UpdateBillingAddressSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n BillingAddressActionType.UpdateBillingAddressFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _updateCustomerConsent(\n { email, acceptsAbandonedCartEmails, acceptsMarketingNewsletter }: GuestCredentials,\n options?: RequestOptions,\n ): Observable {\n if (\n (acceptsAbandonedCartEmails === undefined || acceptsAbandonedCartEmails === null) &&\n (acceptsMarketingNewsletter === undefined || acceptsMarketingNewsletter === null)\n ) {\n return empty();\n }\n\n return this._subscriptionActionCreator.updateSubscriptions(\n {\n email,\n acceptsMarketingNewsletter: acceptsMarketingNewsletter || false,\n acceptsAbandonedCartEmails: acceptsAbandonedCartEmails || false,\n },\n options,\n );\n }\n\n private _createOrUpdateBillingAddress(\n checkoutId: string,\n address: Partial,\n isBillingFixExperimentEnabled: boolean,\n hasBillingAddress: boolean,\n options?: RequestOptions,\n ): Promise> {\n if (isBillingFixExperimentEnabled) {\n if (!hasBillingAddress) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n\n if (!address.id) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\n\nconst DEFAULT_PARAMS = {\n include: [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n ].join(','),\n};\n\nexport default class BillingAddressRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n });\n }\n\n updateAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = address;\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, { params: DEFAULT_PARAMS, body, headers, timeout });\n }\n}\n","import { Action, createAction, createDataStore, ReadableDataStore } from '@bigcommerce/data-store';\n\nenum ProjectionActionType {\n Synchronize = 'SYNCHRONIZE',\n}\n\ninterface SynchronizeAction extends Action {\n type: ProjectionActionType.Synchronize;\n payload: TState;\n}\n\nexport interface DataStoreProjection\n extends ReadableDataStore {\n notifyState(): void;\n}\n\nexport default function createDataStoreProjection(\n store: ReadableDataStore,\n stateTransformer: (state: TState) => TTransformedState,\n): DataStoreProjection {\n const projection = createDataStore<\n TState | undefined,\n SynchronizeAction,\n TTransformedState\n >(\n (state, action) =>\n action.type === ProjectionActionType.Synchronize ? action.payload : state,\n store.getState(),\n { stateTransformer },\n );\n\n store.subscribe(\n (state) => {\n projection.dispatch(\n createAction(ProjectionActionType.Synchronize, state) as SynchronizeAction,\n );\n },\n { initial: false },\n );\n\n return projection;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ErrorActionType {\n ClearError = 'CLEAR_ERROR',\n}\n\nexport type ErrorAction = ClearErrorAction;\n\nexport interface ClearErrorAction extends Action {\n type: ErrorActionType.ClearError;\n payload: Error;\n}\n","import { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default class ErrorActionCreator {\n clearError(error: Error): ClearErrorAction {\n return {\n type: ErrorActionType.ClearError,\n payload: error,\n };\n }\n}\n","export default function getEnvironment(): string {\n try {\n return process.env.NODE_ENV || 'development';\n } catch (e) {\n return 'development';\n }\n}\n","import Logger from './logger';\n\ntype keys = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\nexport default class ConsoleLogger implements Logger {\n constructor(private _console?: Console) {}\n\n log(...messages: any[]): void {\n this._logToConsole('log', ...messages);\n }\n\n info(...messages: any[]): void {\n this._logToConsole('info', ...messages);\n }\n\n warn(...messages: any[]): void {\n this._logToConsole('warn', ...messages);\n }\n\n error(...messages: any[]): void {\n this._logToConsole('error', ...messages);\n }\n\n debug(...messages: any[]): void {\n this._logToConsole('debug', ...messages);\n }\n\n private _logToConsole(type: keys, ...messages: any[]): void {\n if (!this._console || !this._console[type]) {\n return;\n }\n\n this._console[type].call(this._console, ...messages);\n }\n}\n","import Logger from './logger';\n\nexport default class NoopLogger implements Logger {\n log(): void {}\n\n info(): void {}\n\n warn(): void {}\n\n error(): void {}\n\n debug(): void {}\n}\n","import { getEnvironment } from '../utility';\n\nimport createLogger from './create-logger';\nimport Logger from './logger';\n\nconst logger = createLogger(getEnvironment() !== 'test');\n\nexport default function getDefaultLogger(): Logger {\n return logger;\n}\n","import ConsoleLogger from './console-logger';\nimport Logger from './logger';\nimport NoopLogger from './noop-logger';\n\nexport default function createLogger(isEnabled = true): Logger {\n if (!isEnabled) {\n return new NoopLogger();\n }\n\n return new ConsoleLogger(console);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/memoize\");","import { Action } from '@bigcommerce/data-store';\n\nimport Config from './config';\n\nexport enum ConfigActionType {\n LoadConfigRequested = 'LOAD_CONFIG_REQUESTED',\n LoadConfigSucceeded = 'LOAD_CONFIG_SUCCEEDED',\n LoadConfigFailed = 'LOAD_CONFIG_FAILED',\n}\n\nexport type LoadConfigAction =\n | LoadConfigRequestedAction\n | LoadConfigSucceededAction\n | LoadConfigFailedAction;\n\nexport interface LoadConfigRequestedAction extends Action {\n type: ConfigActionType.LoadConfigRequested;\n}\n\nexport interface LoadConfigSucceededAction extends Action {\n type: ConfigActionType.LoadConfigSucceeded;\n}\n\nexport interface LoadConfigFailedAction extends Action {\n type: ConfigActionType.LoadConfigFailed;\n}\n","import cacheAction from './cache-action';\nimport isActionOptions from './is-action-options';\n\nexport default function cachableActionDecorator any>(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n const memoizedMethods = new WeakMap();\n\n function decorateMethod(this: object, method: TMethod): TMethod {\n return ((...args: any[]) => {\n const lastArg = args[args.length - 1];\n const { useCache } = isActionOptions(lastArg) ? lastArg : { useCache: false };\n\n if (!useCache) {\n return method.call(this, ...args);\n }\n\n const instanceMethods = memoizedMethods.get(this) || {};\n\n if (!memoizedMethods.get(this)) {\n memoizedMethods.set(this, instanceMethods);\n }\n\n if (!instanceMethods[key]) {\n instanceMethods[key] = cacheAction(method);\n }\n\n return instanceMethods[key].call(this, ...args);\n }) as TMethod;\n }\n\n return {\n get() {\n if (typeof descriptor.value !== 'function') {\n throw new Error('Decorator should be used in functions');\n }\n\n const value = decorateMethod.call(this, descriptor.value);\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n };\n}\n","import ActionOptions from './action-options';\n\nexport default function isActionOptions(param: any): param is ActionOptions {\n return param && typeof param.useCache === 'boolean';\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { memoize } from '@bigcommerce/memoize';\nimport { isEqual } from 'lodash';\nimport { from, Observable } from 'rxjs';\nimport { shareReplay } from 'rxjs/operators';\n\nexport default function cacheAction(fn: TFunction): TFunction {\n function decoratedFn(this: any, ...args: any[]) {\n const action = fn.call(this, ...args);\n\n if (action instanceof Observable) {\n return from(action).pipe(shareReplay());\n }\n\n if (typeof action === 'function') {\n return memoize((store) => from(action(store)).pipe(shareReplay()), { isEqual });\n }\n\n return action;\n }\n\n return memoize(decoratedFn as TFunction, { isEqual });\n}\n\ntype CreateActionFn = (...args: any[]) => Observable | ThunkAction | Action;\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\n\nimport { ConfigRequestSender } from '.';\n\nexport default class ConfigActionCreator {\n constructor(private _configRequestSender: ConfigRequestSender) {}\n\n @cachableAction\n loadConfig(options?: RequestOptions & ActionOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ConfigActionType.LoadConfigRequested));\n\n this._configRequestSender\n .loadConfig(options)\n .then((response) => {\n observer.next(\n createAction(ConfigActionType.LoadConfigSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(ConfigActionType.LoadConfigFailed, response));\n });\n });\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error when we are unable to retrieve a checkout object from the\n * server using the provided ID. It could be because the shopper does not have\n * permission to view the object, or the ID itself is invalid.\n */\nexport default class CheckoutNotAvailableError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'CheckoutNotAvailableError';\n this.type = 'checkout_not_available';\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutNotAvailableError } from '../checkout/errors';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Config from './config';\n\nexport default class ConfigRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadConfig({ timeout, params }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/checkout-settings';\n\n return this._requestSender\n .get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum CouponActionType {\n ApplyCouponRequested = 'APPLY_COUPON_REQUESTED',\n ApplyCouponSucceeded = 'APPLY_COUPON_SUCCEEDED',\n ApplyCouponFailed = 'APPLY_COUPON_FAILED',\n\n RemoveCouponRequested = 'REMOVE_COUPON_REQUESTED',\n RemoveCouponSucceeded = 'REMOVE_COUPON_SUCCEEDED',\n RemoveCouponFailed = 'REMOVE_COUPON_FAILED',\n}\n\nexport type CouponAction = ApplyCouponAction | RemoveCouponAction;\n\nexport type ApplyCouponAction =\n | ApplyCouponRequestedAction\n | ApplyCouponSucceededAction\n | ApplyCouponFailedAction;\n\nexport type RemoveCouponAction =\n | RemoveCouponRequestedAction\n | RemoveCouponSucceededAction\n | RemoveCouponFailedAction;\n\nexport interface ApplyCouponRequestedAction extends Action {\n type: CouponActionType.ApplyCouponRequested;\n}\n\nexport interface ApplyCouponSucceededAction extends Action {\n type: CouponActionType.ApplyCouponSucceeded;\n}\n\nexport interface ApplyCouponFailedAction extends Action> {\n type: CouponActionType.ApplyCouponFailed;\n}\n\nexport interface RemoveCouponRequestedAction extends Action {\n type: CouponActionType.RemoveCouponRequested;\n}\n\nexport interface RemoveCouponSucceededAction extends Action {\n type: CouponActionType.RemoveCouponSucceeded;\n}\n\nexport interface RemoveCouponFailedAction extends Action {\n type: CouponActionType.RemoveCouponFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyCouponAction,\n CouponAction,\n CouponActionType,\n RemoveCouponAction,\n} from './coupon-actions';\nimport CouponRequestSender from './coupon-request-sender';\n\nexport default class CouponActionCreator {\n constructor(private _couponRequestSender: CouponRequestSender) {}\n\n applyCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.ApplyCouponRequested));\n\n this._couponRequestSender\n .applyCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.ApplyCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.ApplyCouponFailed, response),\n );\n });\n });\n }\n\n removeCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.RemoveCouponRequested));\n\n this._couponRequestSender\n .removeCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.RemoveCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.RemoveCouponFailed, response),\n );\n });\n });\n }\n}\n","const CHECKOUT_DEFAULT_INCLUDES = [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'customer.customerGroup',\n 'payments',\n 'promotions.banners',\n];\n\nexport default CHECKOUT_DEFAULT_INCLUDES;\n","export enum CheckoutIncludes {\n AvailableShippingOptions = 'consignments.availableShippingOptions',\n PhysicalItemsCategoryNames = 'cart.lineItems.physicalItems.categoryNames',\n DigitalItemsCategoryNames = 'cart.lineItems.digitalItems.categoryNames',\n}\n\nexport default interface CheckoutParams {\n include?: CheckoutIncludes[] | CheckoutIncludeParam;\n}\n\nexport type CheckoutIncludeParam = {\n [key in CheckoutIncludes]?: boolean;\n};\n","import { uniq } from 'lodash';\n\nexport default function joinIncludes(includes: T[]): string {\n return uniq(includes).join(',');\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES, CheckoutIncludes } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class CouponRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n body: { couponCode },\n });\n }\n\n removeCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons/${couponCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum GiftCertificateActionType {\n ApplyGiftCertificateRequested = 'APPLY_GIFT_CERTIFICATE_REQUESTED',\n ApplyGiftCertificateSucceeded = 'APPLY_GIFT_CERTIFICATE_SUCCEEDED',\n ApplyGiftCertificateFailed = 'APPLY_GIFT_CERTIFICATE_FAILED',\n\n RemoveGiftCertificateRequested = 'REMOVE_GIFT_CERTIFICATE_REQUESTED',\n RemoveGiftCertificateSucceeded = 'REMOVE_GIFT_CERTIFICATE_SUCCEEDED',\n RemoveGiftCertificateFailed = 'REMOVE_GIFT_CERTIFICATE_FAILED',\n}\n\nexport type GiftCertificateAction = ApplyGiftCertificateAction | RemoveGiftCertificateAction;\n\nexport type ApplyGiftCertificateAction =\n | ApplyGiftCertificateRequestedAction\n | ApplyGiftCertificateSucceededAction\n | ApplyGiftCertificateFailedAction;\n\nexport type RemoveGiftCertificateAction =\n | RemoveGiftCertificateRequestedAction\n | RemoveGiftCertificateSucceededAction\n | RemoveGiftCertificateFailedAction;\n\nexport interface ApplyGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateRequested;\n}\n\nexport interface ApplyGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateSucceeded;\n}\n\nexport interface ApplyGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.ApplyGiftCertificateFailed;\n}\n\nexport interface RemoveGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateRequested;\n}\n\nexport interface RemoveGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateSucceeded;\n}\n\nexport interface RemoveGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.RemoveGiftCertificateFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyGiftCertificateAction,\n GiftCertificateActionType,\n RemoveGiftCertificateAction,\n} from './gift-certificate-actions';\n\nimport { GiftCertificateRequestSender } from '.';\n\nexport default class GiftCertificateActionCreator {\n constructor(private _giftCertificateRequestSender: GiftCertificateRequestSender) {}\n\n applyGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.ApplyGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .applyGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.ApplyGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.ApplyGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n\n removeGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.RemoveGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .removeGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.RemoveGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.RemoveGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class GiftCertificateRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n });\n }\n\n removeGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates/${giftCertificateCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return 'resolveIds' in module;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Factory from './factory';\n\nexport default class Registry {\n private _factories: { [key: string]: Factory };\n private _instances: { [key: string]: T };\n private _defaultToken: string;\n private _useFallback: string | boolean;\n private _tokenResolver: (token: string, registeredTokens: string[]) => string | undefined;\n\n constructor(options?: RegistryOptions) {\n this._factories = {};\n this._instances = {};\n this._defaultToken = options?.defaultToken ?? 'default';\n this._useFallback = options?.useFallback ?? true;\n this._tokenResolver = options?.tokenResolver ?? ((token) => token);\n }\n\n get(token?: K, cacheToken?: string): T {\n try {\n return this._getInstance(\n token || this._defaultToken,\n cacheToken || token || this._defaultToken,\n );\n } catch (error) {\n if (!this._useFallback) {\n throw error;\n }\n\n return this._getInstance(this._defaultToken, cacheToken || this._defaultToken);\n }\n }\n\n register(token: K, factory: Factory): void {\n if (this._hasFactory(token)) {\n throw new InvalidArgumentError(`'${token}' is already registered.`);\n }\n\n this._factories[token] = factory;\n }\n\n protected _hasFactory(token: string): boolean {\n return !!this._factories[token];\n }\n\n private _hasInstance(token: string): boolean {\n return !!this._instances[token];\n }\n\n private _getInstance(token: string, cacheToken: string): T {\n if (!this._hasInstance(cacheToken)) {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories));\n const factory = resolvedToken && this._factories[resolvedToken];\n\n if (!factory) {\n throw new InvalidArgumentError(`'${token}' is not registered.`);\n }\n\n this._instances[cacheToken] = factory();\n }\n\n return this._instances[cacheToken];\n }\n}\n\nexport interface RegistryOptions {\n defaultToken?: string;\n useFallback?: boolean;\n tokenResolver?(token: string, registeredTokens: string[]): string | undefined;\n}\n","import { getDefaultLogger } from '../log';\nimport { getEnvironment } from '../utility';\n\nimport Factory from './factory';\nimport Registry from './registry';\n\nexport default class ResolveIdRegistry {\n private _registry: Registry;\n\n constructor(private _useFallback = false) {\n this._registry = new Registry({\n tokenResolver: this._resolveToken.bind(this),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n register(resolveId: TToken, factory: Factory): void {\n this._registry.register(this._encodeToken(resolveId), factory);\n }\n\n private _encodeToken(resolveId: TToken): string {\n return btoa(JSON.stringify(resolveId));\n }\n\n private _decodeToken(token: string): TToken {\n return JSON.parse(atob(token));\n }\n\n private _resolveToken(token: string, registeredTokens: string[]): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{ token: string; matches: number; default: boolean }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = { token: registeredToken, matches: 0, default: false };\n\n for (const [key, value] of Object.entries(resolverId)) {\n if (key in query && query[key] !== value) {\n result.matches = 0;\n break;\n }\n\n if (key in query && query[key] === value) {\n result.matches++;\n }\n\n if (key === 'default' && value === true) {\n result.default = true;\n }\n }\n\n results.push(result);\n });\n\n const matchedResults = results\n .sort((a, b) => b.matches - a.matches)\n .filter((result) => result.matches > 0);\n\n if (matchedResults.length > 1 && matchedResults[0].matches === matchedResults[1].matches) {\n if (getEnvironment() === 'development') {\n getDefaultLogger().warn(\n 'The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.',\n );\n }\n }\n\n const matched = matchedResults[0];\n\n if (matched && matched.token) {\n return matched.token;\n }\n\n if (this._useFallback) {\n const defaultToken = results.find((result) => result.default)?.token;\n\n if (defaultToken) {\n return defaultToken;\n }\n }\n\n throw new Error('Unable to resolve to a registered token with the provided token.');\n }\n}\n","import CustomError from './custom-error';\nimport setPrototypeOf from './set-prototype-of';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Cart } from '../cart';\n\nimport getLineItemsCount from './getLineItemsCount';\n\nexport default function getShippableItemsCount(cart: Cart): number {\n return getLineItemsCount(cart.lineItems.physicalItems.filter((item) => !item.addedByPromotion));\n}\n","import { reduce } from 'lodash';\n\nimport { LineItem } from '../cart';\n\nexport default function getLineItemsCount(lineItems: LineItem[]): number {\n return reduce(lineItems, (total, item: LineItem) => total + item.quantity, 0);\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import {\n Cart,\n Checkout,\n PaymentIntegrationSelectors,\n PaymentMethod,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\n\nexport interface AmazonPayV2Options {\n environment: EnvironmentType;\n}\n\nexport interface AmazonPayV2SDK {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Pay: AmazonPayV2Client;\n}\n\nexport interface RequestConfig {\n createCheckoutSessionConfig: AmazonPayV2CheckoutSessionConfig;\n estimatedOrderAmount?: AmazonPayV2Price;\n productType?: AmazonPayV2PayOptions;\n}\n\nexport interface AmazonPayV2Button {\n /**\n * Allows you to define custom actions.\n */\n onClick: (callback: () => void | Promise) => void;\n\n /**\n * Initiates the Amazon Pay checkout.\n */\n initCheckout(requestConfig: RequestConfig): void;\n}\n\nexport type AmazonPayV2ButtonParameters = AmazonPayV2ButtonParams | AmazonPayV2NewButtonParams;\n\nexport interface AmazonPayV2Client {\n /**\n * Render the Amazon Pay button to a HTML container element.\n *\n * @param containerId - HTML element id.\n * @param params - Button rendering params.\n */\n renderButton(containerId: string, params: AmazonPayV2ButtonParameters): AmazonPayV2Button;\n\n /**\n * Bind click events to HTML elements, so that when the element is clicked, the buyer can select a different shipping address or payment method.\n *\n * @param buttonId - HTML element id.\n * @param options - Element binding options.\n */\n bindChangeAction(buttonId: string, options: AmazonPayV2ChangeActionOptions): void;\n\n /**\n * Allow buyers to sign out from their Amazon account.\n */\n signout(): void;\n}\n\nexport interface AmazonPayV2HostWindow extends Window {\n amazon?: AmazonPayV2SDK;\n}\n\nexport interface AmazonPayV2ButtonConfig {\n /**\n * Amazon Pay merchant account identifier.\n */\n merchantId: string;\n\n /**\n * Placement of the Amazon Pay button on your website.\n */\n placement: AmazonPayV2Placement;\n\n /**\n * Ledger currency provided during registration for the given merchant identifier.\n */\n ledgerCurrency: AmazonPayV2LedgerCurrency;\n\n /**\n * Product type selected for checkout. Default is 'PayAndShip'.\n */\n productType?: AmazonPayV2PayOptions;\n\n /**\n * Color of the Amazon Pay button.\n */\n buttonColor?: AmazonPayV2ButtonColor;\n\n /**\n * Language used to render the button and text on Amazon Pay hosted pages.\n */\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n\n /**\n * Sets button to Sandbox environment. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix. Default is false.\n */\n sandbox?: boolean;\n\n /**\n * Sets Amazon Pay button design.\n */\n design?: AmazonPayV2ButtonDesign;\n}\n\nexport interface AmazonPayV2ButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Configuration for calling the endpoint to Create Checkout Session.\n */\n createCheckoutSession: AmazonPayV2CheckoutSession;\n}\n\nexport interface AmazonPayV2NewButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Credential provided by Amazon Pay. You must also set the `sandbox`\n * parameter if your `publicKeyId` does not have an environment prefix.\n */\n publicKeyId?: string;\n\n /**\n * It does not have to match the final order amount if the buyer updates\n * their order after starting checkout. Amazon Pay will use this value to\n * assess transaction risk and prevent buyers from selecting payment methods\n * that can't be used to process the order.\n */\n estimatedOrderAmount?: AmazonPayV2Price;\n\n /**\n * Create Checkout Session configuration.\n */\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n}\n\nexport interface AmazonPayV2CheckoutSession {\n /**\n * Endpoint URL to Create Checkout Session.\n */\n url: string;\n\n /**\n * HTTP request method. Default is 'POST'.\n */\n method?: 'GET' | 'POST';\n\n /**\n * Checkout Session ID parameter in the response. Default is 'checkoutSessionId'.\n */\n extractAmazonCheckoutSessionId?: string;\n}\n\nexport interface AmazonPayV2CheckoutSessionConfig {\n /**\n * A payload that Amazon Pay will use to create a Checkout Session object.\n */\n payloadJSON: string;\n\n /**\n * Payload's signature.\n */\n signature: string;\n\n /**\n * Credential provided by Amazon Pay. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix.\n */\n publicKeyId?: string;\n}\n\nexport interface AmazonPayV2Price {\n /**\n * Transaction amount.\n */\n amount: string;\n\n /**\n * Transaction currency code in ISO 4217 format. Example: USD.\n */\n currencyCode: string;\n}\n\nexport type AmazonPayV2ChangeActionType = 'changeAddress' | 'changePayment';\n\nexport interface AmazonPayV2ChangeActionOptions {\n /**\n * Amazon Pay Checkout Session identifier.\n */\n amazonCheckoutSessionId: string;\n\n /**\n * Update requested by the buyer.\n */\n changeAction: AmazonPayV2ChangeActionType;\n}\n\nexport const amazonPayV2Regions: { [key: string]: string } = {\n de: 'eu',\n jp: 'fe',\n uk: 'eu',\n us: 'na',\n};\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum AmazonPayV2CheckoutLanguage {\n en_US = 'en_US',\n en_GB = 'en_GB',\n de_DE = 'de_DE',\n fr_FR = 'fr_FR',\n it_IT = 'it_IT',\n es_ES = 'es_ES',\n ja_JP = 'ja_JP',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/* eslint-disable @typescript-eslint/no-shadow */\nexport enum AmazonPayV2Placement {\n /** Initial or main page. */\n Home = 'Home',\n\n /** Product details page. */\n Product = 'Product',\n\n /** Cart review page before buyer starts checkout. */\n Cart = 'Cart',\n\n /** Any page after buyer starts checkout. */\n Checkout = 'Checkout',\n\n /** Any page that doesn't fit the previous descriptions. */\n Other = 'Other',\n}\n/* eslint-enable @typescript-eslint/no-shadow */\n\nexport enum AmazonPayV2LedgerCurrency {\n USD = 'USD',\n EUR = 'EUR',\n GBP = 'GBP',\n JPY = 'JPY',\n}\n\nexport enum AmazonPayV2PayOptions {\n /** Select this product type if you need the buyer's shipping details. */\n PayAndShip = 'PayAndShip',\n\n /** Select this product type if you do not need the buyer's shipping details. */\n PayOnly = 'PayOnly',\n}\n\nexport enum AmazonPayV2ButtonColor {\n Gold = 'Gold',\n LightGray = 'LightGray',\n DarkGray = 'DarkGray',\n}\n\nexport enum AmazonPayV2ButtonDesign {\n C0001 = 'C0001',\n}\n\n// TODO: after migration AmazonPay strategies to integration package\n// should be removed\n// and replaced usage with \nexport interface InternalCheckoutSelectors {\n cart: {\n getCart: () => Cart | undefined;\n };\n checkout: {\n getCheckout: () => Checkout | undefined;\n };\n config: {\n getStoreConfigOrThrow: () => StoreConfig;\n };\n paymentMethods: {\n getPaymentMethodOrThrow: (methodId: string) => PaymentMethod;\n };\n}\n\nexport interface AmazonPayV2InitializeOptions {\n buttonColor?: AmazonPayV2ButtonColor;\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n checkoutSessionMethod?: 'GET' | 'POST';\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n extractAmazonCheckoutSessionId?: string;\n ledgerCurrency?: AmazonPayV2LedgerCurrency;\n publicKeyId?: string;\n region?: string;\n isButtonMicroTextDisabled?: boolean;\n paymentToken?: string;\n}\n\nexport interface AmazonPayV2ButtonRenderingOptions {\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors;\n containerId: string;\n decoupleCheckoutInitiation?: boolean;\n methodId: string;\n buttonColor?: AmazonPayV2ButtonColor;\n options?: AmazonPayV2ButtonParameters;\n placement: AmazonPayV2Placement;\n isButtonMicroTextDisabled?: boolean;\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport interface AmazonPayAdditionalActionErrorBody {\n status: string;\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n","import {\n CheckoutSettings,\n getShippableItemsCount,\n guard,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationSelectors,\n PaymentMethod,\n StoreProfile,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AmazonPayV2Button,\n AmazonPayV2ButtonColor,\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonDesign,\n AmazonPayV2ButtonParameters,\n AmazonPayV2ButtonRenderingOptions,\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2NewButtonParams,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n AmazonPayV2Price,\n AmazonPayV2SDK,\n InternalCheckoutSelectors,\n RequestConfig,\n} from './amazon-pay-v2';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\nimport { isInternalCheckoutSelectors } from './isInternalCheckoutSelectors';\n\nexport default class AmazonPayV2PaymentProcessor {\n private amazonPayV2SDK?: AmazonPayV2SDK;\n private buttonParentContainer?: HTMLDivElement;\n private amazonPayV2Button?: AmazonPayV2Button;\n private isBuyNowFlow?: boolean;\n\n constructor(private amazonPayV2ScriptLoader: AmazonPayV2ScriptLoader) {}\n\n async initialize(paymentMethod: PaymentMethod): Promise {\n this.amazonPayV2SDK = await this.amazonPayV2ScriptLoader.load(paymentMethod);\n this.buttonParentContainer =\n this.buttonParentContainer || this.createAmazonPayButtonParentContainer();\n }\n\n deinitialize(): Promise {\n this.amazonPayV2Button = undefined;\n this.buttonParentContainer?.remove();\n this.buttonParentContainer = undefined;\n this.amazonPayV2SDK = undefined;\n\n return Promise.resolve();\n }\n\n bindButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n ): void {\n this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${buttonId}`, {\n amazonCheckoutSessionId: sessionId,\n changeAction,\n });\n }\n\n createButton(containerId: string, options: AmazonPayV2ButtonParameters): void {\n this.amazonPayV2Button = this.getAmazonPayV2SDK().Pay.renderButton(\n `#${containerId}`,\n options,\n );\n }\n\n prepareCheckout(createCheckoutSessionConfig: Required) {\n const requestConfig = this.prepareRequestConfig(createCheckoutSessionConfig);\n\n this.getAmazonPayV2Button().onClick(() => {\n this.getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n prepareCheckoutWithCreationRequestConfig(\n createCheckoutConfig: () => Promise<\n | {\n createCheckoutSessionConfig: Required;\n estimatedOrderAmount: AmazonPayV2Price;\n productType: AmazonPayV2PayOptions;\n }\n | undefined\n >,\n ) {\n this.getAmazonPayV2Button().onClick(async () => {\n const config = await createCheckoutConfig();\n\n if (config) {\n const requestConfig = this.prepareRequestConfig(\n config.createCheckoutSessionConfig,\n config.estimatedOrderAmount,\n config.productType,\n );\n\n this.getAmazonPayV2Button().initCheckout(requestConfig);\n }\n });\n }\n\n async signout(): Promise {\n if (this.amazonPayV2SDK) {\n this.amazonPayV2SDK.Pay.signout();\n }\n\n return Promise.resolve();\n }\n\n renderAmazonPayButton({\n buttonColor,\n checkoutState,\n containerId,\n decoupleCheckoutInitiation = false,\n methodId,\n options,\n placement,\n isButtonMicroTextDisabled = false,\n }: AmazonPayV2ButtonRenderingOptions): HTMLDivElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\n }\n\n const { id: parentContainerId } = container.appendChild(this.getButtonParentContainer());\n\n if (options && isButtonMicroTextDisabled) {\n options.design = AmazonPayV2ButtonDesign.C0001;\n }\n\n const amazonPayV2ButtonOptions =\n options ??\n this.getAmazonPayV2ButtonOptions(\n checkoutState,\n methodId,\n placement,\n decoupleCheckoutInitiation,\n buttonColor,\n );\n\n this.createButton(parentContainerId, amazonPayV2ButtonOptions);\n\n return this.getButtonParentContainer();\n }\n\n updateBuyNowFlowFlag(isBuyNowFlow?: boolean) {\n this.isBuyNowFlow = Boolean(isBuyNowFlow);\n }\n\n /**\n * @internal\n */\n isPh4Enabled(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n const isPh4Enabled = !!features['PROJECT-3483.amazon_pay_ph4'];\n const isPh4UsOnly = !!features['INT-6885.amazon_pay_ph4_us_only'];\n\n if (isPh4Enabled && isPh4UsOnly) {\n return storeCountryCode === 'US';\n }\n\n return isPh4Enabled;\n }\n\n private prepareRequestConfig(\n createCheckoutSessionConfig: Required,\n estimatedOrderAmount?: AmazonPayV2Price,\n productType?: AmazonPayV2PayOptions,\n ): RequestConfig {\n const { publicKeyId, ...signedPayload } = createCheckoutSessionConfig;\n\n return {\n createCheckoutSessionConfig: this.isEnvironmentSpecific(publicKeyId)\n ? signedPayload\n : createCheckoutSessionConfig,\n ...(estimatedOrderAmount && { estimatedOrderAmount }),\n ...(productType && { productType }),\n };\n }\n\n private createAmazonPayButtonParentContainer(): HTMLDivElement {\n const uid = Math.random().toString(16).substr(-4);\n const parentContainer = document.createElement('div');\n\n parentContainer.id = `amazonpay_button_parent_container_${uid}`;\n\n return parentContainer;\n }\n\n private getAmazonPayV2ButtonOptions(\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors,\n methodId: string,\n placement: AmazonPayV2Placement,\n decoupleCheckoutInitiation = false,\n buttonColor = AmazonPayV2ButtonColor.Gold,\n ): AmazonPayV2ButtonParameters {\n const { getCart, getCheckout, getStoreConfigOrThrow, getPaymentMethodOrThrow } =\n this.getCheckoutState(checkoutState);\n const {\n config: { merchantId, testMode },\n initializationData,\n } = getPaymentMethodOrThrow(methodId);\n\n if (!initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n checkoutLanguage,\n checkoutSessionMethod,\n createCheckoutSessionConfig,\n extractAmazonCheckoutSessionId,\n ledgerCurrency,\n publicKeyId = '',\n isButtonMicroTextDisabled,\n } = initializationData;\n\n if (!merchantId || !ledgerCurrency || !createCheckoutSessionConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const buttonBaseConfig: AmazonPayV2ButtonConfig = {\n merchantId,\n ledgerCurrency,\n checkoutLanguage,\n placement,\n buttonColor,\n ...(isButtonMicroTextDisabled ? { design: AmazonPayV2ButtonDesign.C0001 } : {}),\n };\n\n if (this.isBuyNowFlow) {\n return {\n ...buttonBaseConfig,\n sandbox: !!testMode,\n };\n }\n\n const cart = getCart();\n\n buttonBaseConfig.productType =\n cart && getShippableItemsCount(cart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip;\n\n const {\n checkoutSettings: { features },\n storeProfile: { shopPath, storeCountryCode },\n } = getStoreConfigOrThrow();\n\n if (this.isPh4Enabled(features, storeCountryCode)) {\n const amount = getCheckout()?.outstandingBalance.toString();\n const currencyCode = cart?.currency.code;\n const buttonOptions: AmazonPayV2NewButtonParams = { ...buttonBaseConfig };\n let tmpConfig: AmazonPayV2CheckoutSessionConfig;\n\n if (this.isEnvironmentSpecific(publicKeyId)) {\n buttonOptions.publicKeyId = publicKeyId;\n tmpConfig = createCheckoutSessionConfig;\n } else {\n buttonOptions.sandbox = !!testMode;\n tmpConfig = { ...createCheckoutSessionConfig, publicKeyId };\n }\n\n if (!decoupleCheckoutInitiation) {\n buttonOptions.createCheckoutSessionConfig = tmpConfig;\n }\n\n if (amount && currencyCode) {\n buttonOptions.estimatedOrderAmount = { amount, currencyCode };\n }\n\n return buttonOptions;\n }\n\n const createCheckoutSession = {\n method: checkoutSessionMethod,\n url: features['INT-5826.amazon_relative_url']\n ? `/remote-checkout/${methodId}/payment-session`\n : `${shopPath}/remote-checkout/${methodId}/payment-session`,\n extractAmazonCheckoutSessionId,\n };\n\n return {\n ...buttonBaseConfig,\n createCheckoutSession,\n sandbox: !!testMode,\n };\n }\n\n private isEnvironmentSpecific(publicKeyId: string): boolean {\n return /^(SANDBOX|LIVE)/.test(publicKeyId);\n }\n\n private getAmazonPayV2SDK(): AmazonPayV2SDK {\n return this.getOrThrow(this.amazonPayV2SDK);\n }\n\n private getButtonParentContainer(): HTMLDivElement {\n return this.getOrThrow(this.buttonParentContainer);\n }\n\n private getAmazonPayV2Button(): AmazonPayV2Button {\n return this.getOrThrow(this.amazonPayV2Button);\n }\n\n private getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n // INFO: need this mapping while we have strategies in core and in integration package at the same time\n private getCheckoutState(\n checkoutState: InternalCheckoutSelectors | PaymentIntegrationSelectors,\n ): Pick<\n PaymentIntegrationSelectors,\n 'getCart' | 'getCheckout' | 'getStoreConfigOrThrow' | 'getPaymentMethodOrThrow'\n > {\n if (isInternalCheckoutSelectors(checkoutState)) {\n return {\n getCart: checkoutState.cart.getCart,\n getCheckout: checkoutState.checkout.getCheckout,\n getStoreConfigOrThrow: checkoutState.config.getStoreConfigOrThrow,\n getPaymentMethodOrThrow: (methodId: string) =>\n checkoutState.paymentMethods.getPaymentMethodOrThrow(methodId),\n };\n }\n\n return checkoutState;\n }\n}\n","import { InternalCheckoutSelectors } from './amazon-pay-v2';\n\nexport function isInternalCheckoutSelectors(\n checkoutSelectors: unknown,\n): checkoutSelectors is InternalCheckoutSelectors {\n return (\n typeof checkoutSelectors === 'object' &&\n checkoutSelectors !== null &&\n 'cart' in checkoutSelectors &&\n 'checkout' in checkoutSelectors &&\n 'config' in checkoutSelectors &&\n 'paymentMethods' in checkoutSelectors\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AmazonPayV2HostWindow,\n AmazonPayV2InitializeOptions,\n amazonPayV2Regions,\n AmazonPayV2SDK,\n} from './amazon-pay-v2';\n\nexport default class AmazonPayV2ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private windowWithAmazonPay: AmazonPayV2HostWindow = window,\n ) {}\n\n async load(method: PaymentMethod): Promise {\n const { initializationData } = method;\n const region = initializationData?.region || 'us';\n\n const amazonPayV2Region = amazonPayV2Regions[region];\n\n await this.scriptLoader.loadScript(\n `https://static-${amazonPayV2Region}.payments-amazon.com/checkout.js`,\n );\n\n if (!this.windowWithAmazonPay.amazon) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.windowWithAmazonPay.amazon;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default function createAmazonPayV2PaymentProcessor(): AmazonPayV2PaymentProcessor {\n return new AmazonPayV2PaymentProcessor(new AmazonPayV2ScriptLoader(getScriptLoader()));\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function toResolvableModule(\n module: TModule,\n resolveIds: TIdentifier[],\n): ResolvableModule {\n return Object.assign(module, { resolveIds });\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import {\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithAmazonPayV2CustomerInitializeOptions } from './amazon-pay-v2-customer-initialize-options';\n\nexport default class AmazonPayV2CustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithAmazonPayV2CustomerInitializeOptions,\n ): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId || !amazonpay?.container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this.paymentIntegrationService.getState(),\n containerId: amazonpay.container,\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n }\n\n async deinitialize(): Promise {\n await this.amazonPayV2PaymentProcessor.deinitialize();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Amazon, the shopper must click on \"Amazon Pay\" button.',\n );\n }\n\n async signOut(options?: RequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n\n if (!payment) {\n return;\n }\n\n await this.amazonPayV2PaymentProcessor.signout();\n await this.paymentIntegrationService.remoteCheckoutSignOut(payment.providerId, options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n}\n","import { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2CustomerStrategy from './amazon-pay-v2-customer-strategy';\n\nconst createAmazonPayV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AmazonPayV2CustomerStrategy(\n paymentIntegrationService,\n createAmazonPayV2PaymentProcessor(),\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2CustomerStrategy, [{ id: 'amazonpay' }]);\n","import { StandardError } from './index';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","export * from './braintree';\nexport * from './paypal';\nexport * from './visacheckout';\n\n/**\n *\n * Braintree Module\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string; // Info: authorization uses clientToken as a value\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\n/**\n *\n * Braintree Window\n *\n */\nexport interface BraintreeWindow extends Window {\n client?: BraintreeClientCreator;\n braintreeFastlane?: BraintreeFastlane;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeClientRequestPayload): Promise;\n}\n\nexport interface BraintreeClientRequestPayload {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeClientRequestResponse {\n creditCards: BraintreeHostedFieldsTokenizePayload[];\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean; // Info: this param is needed for fraud detection (should always be 'true')\n paypal?: boolean; // TODO: based on braintree documentation, this param is deprecated, so we dont need it anymore\n riskCorrelationId?: string; // Info: the option is needed for PayPal Analytics\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n// TODO: remove this interface when BraintreeIntegrationService will be removed\nexport interface BraintreeDataCollectors {\n default?: BraintreeDataCollector;\n paypal?: BraintreeDataCollector;\n}\n\n/**\n *\n * Braintree Google Payment\n *\n */\ntype BraintreeGooglePaymentAddressFormat = 'FULL' | 'MIN';\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\nexport interface BraintreeGooglePaymentDataRequestOptions {\n merchantInfo: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n transactionInfo: {\n currencyCode: string;\n totalPriceStatus: TotalPriceStatusType;\n totalPrice: string;\n };\n cardRequirements: {\n billingAddressRequired: boolean;\n billingAddressFormat: BraintreeGooglePaymentAddressFormat;\n };\n emailRequired?: boolean;\n phoneNumberRequired?: boolean;\n shippingAddressRequired?: boolean;\n}\n\nexport interface BraintreeGooglePaymentDataRequest {\n allowedPaymentMethods: string[];\n apiVersion: number;\n cardRequirements: {\n allowedCardNetworks: string[];\n billingAddressFormat: string;\n billingAddressRequired: boolean;\n };\n environment: string;\n i: {\n googleTransactionId: string;\n startTimeMs: number;\n };\n merchantInfo: {\n merchantId: string;\n merchantName: string;\n authJwt?: string;\n };\n paymentMethodTokenizationParameters: {\n parameters: {\n 'braintree:apiVersion': string;\n 'braintree:authorizationFingerprint': string;\n 'braintree:merchantId': string;\n 'braintree:metadata': string;\n 'braintree:sdkVersion': string;\n gateway: string;\n };\n tokenizationType: string;\n };\n shippingAddressRequired: boolean;\n phoneNumberRequired: boolean;\n transactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport type BraintreeGooglePaymentCreator = BraintreeModuleCreator;\n\nexport interface BraintreeGooglePayment extends BraintreeModule {\n createPaymentDataRequest(\n options?: BraintreeGooglePaymentDataRequestOptions,\n ): BraintreeGooglePaymentDataRequest;\n}\n\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n bin: string;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested?: boolean;\n showLoader?: boolean;\n bin?: string;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n addFrame?(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n removeFrame?(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\nexport interface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree US Bank Account (ACH)\n *\n */\nexport type BraintreeUsBankAccountCreator = BraintreeModuleCreator;\n\nexport interface BraintreeUsBankAccount {\n tokenize(\n options: BraintreeUsBankAccountTokenizationOptions,\n ): Promise;\n}\n\nexport interface BraintreeUsBankAccountTokenizationOptions {\n bankDetails: BraintreeUsBankAccountDetails;\n mandateText: string;\n}\n\nexport interface BraintreeUsBankAccountTokenizationResponse {\n nonce: string;\n details: BraintreeTokenizationDetails;\n}\n\nexport interface BraintreeUsBankAccountDetails {\n accountNumber: string;\n routingNumber: string;\n ownershipType: string;\n accountType: string;\n firstName?: string;\n lastName?: string;\n businessName?: string;\n billingAddress: {\n streetAddress: string;\n extendedAddress: string;\n locality: string;\n region: string;\n postalCode: string;\n };\n}\n\n// TODO: move this interface in separate types group if it will be used in another (not ACH) strategies\n// This seems to be an interface which will be used in different places\nexport interface BraintreeTokenizationDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\n/**\n *\n * Braintree Fastlane\n *\n */\nexport type BraintreeFastlaneCreator = BraintreeModuleCreator<\n BraintreeFastlane,\n BraintreeFastlaneConfig\n>;\n\nexport interface BraintreeFastlaneConfig {\n authorization: string;\n client: BraintreeClient;\n deviceData?: string;\n styles?: BraintreeFastlaneStylesOption;\n}\n\nexport interface BraintreeFastlane {\n identity: BraintreeFastlaneIdentity;\n profile: BraintreeFastlaneProfile;\n FastlaneCardComponent: (\n options: BraintreeFastlaneCardComponentOptions,\n ) => Promise;\n events: BraintreeFastlaneEvents;\n}\n\nexport interface BraintreeFastlaneProfile {\n showCardSelector(): Promise;\n showShippingAddressSelector(): Promise;\n}\n\nexport interface BraintreeFastlaneShippingAddressSelectorResponse {\n selectionChanged: boolean;\n selectedAddress: BraintreeFastlaneShippingAddress;\n}\n\nexport interface BraintreeFastlaneShippingAddress {\n name: BraintreeFastlaneProfileName;\n phoneNumber: string;\n id?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress: string;\n extendedAddress?: string;\n locality: string;\n region: string;\n postalCode: string;\n countryCodeNumeric?: number;\n countryCodeAlpha2: string;\n countryCodeAlpha3?: string;\n}\n\nexport interface BraintreeFastlaneProfileName {\n fullName: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface BraintreeFastlaneCardSelectorResponse {\n selectionChanged: boolean;\n selectedCard: BraintreeFastlaneVaultedInstrument;\n}\n\nexport interface BraintreeFastlaneWindow extends Window {\n braintreeFastlane: BraintreeFastlane;\n}\n\nexport interface BraintreeFastlaneIdentity {\n lookupCustomerByEmail(email: string): Promise;\n triggerAuthenticationFlow(\n customerId: string,\n options?: BraintreeFastlaneAuthenticationOptions,\n ): Promise;\n}\n\nexport interface BraintreeFastlaneLookupCustomerByEmailResult {\n customerContextId?: string;\n}\n\nexport interface BraintreeFastlaneAuthenticationOptions {\n styles?: BraintreeFastlaneStylesOption;\n}\n\nexport interface BraintreeFastlaneStylesOption {\n root?: {\n backgroundColorPrimary?: string;\n errorColor?: string;\n fontFamily?: string;\n fontSizeBase?: string;\n padding?: string;\n primaryColor?: string;\n };\n input?: {\n borderRadius?: string;\n borderColor?: string;\n focusBorderColor?: string;\n backgroundColor?: string;\n borderWidth?: string;\n textColorBase?: string;\n };\n toggle?: {\n colorPrimary?: string;\n colorSecondary?: string;\n };\n text?: {\n body?: {\n color?: string;\n fontSize?: string;\n };\n caption?: {\n color?: string;\n fontSize?: string;\n };\n };\n branding?: string; // 'light' | 'dark'\n}\n\nexport enum BraintreeFastlaneAuthenticationState {\n SUCCEEDED = 'succeeded',\n FAILED = 'failed',\n CANCELED = 'cancelled',\n UNRECOGNIZED = 'unrecognized',\n}\n\nexport interface BraintreeFastlaneAuthenticationCustomerResult {\n authenticationState: BraintreeFastlaneAuthenticationState;\n profileData: BraintreeFastlaneProfileData;\n}\n\nexport interface BraintreeFastlaneProfileData {\n fastlaneCustomerAuthAssertionToken: string;\n fastlaneCustomerId: string;\n shippingAddress: BraintreeFastlaneAddress;\n card: BraintreeFastlaneVaultedInstrument;\n name: BraintreeFastlaneName;\n}\n\nexport interface BraintreeFastlaneName {\n firstName: string;\n lastName: string;\n}\n\nexport interface BraintreeFastlaneAddress {\n id?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress: string;\n extendedAddress?: string;\n locality: string;\n region: string;\n postalCode: string;\n countryCodeNumeric?: number;\n countryCodeAlpha2: string;\n countryCodeAlpha3?: string;\n phoneNumber?: string;\n}\n\nexport interface BraintreeFastlaneCardPaymentSource {\n brand: string;\n expiry: string;\n lastDigits: string;\n name?: string;\n billingAddress: BraintreeFastlaneAddress;\n}\n\nexport interface BraintreeFastlanePaymentSource {\n card: BraintreeFastlaneCardPaymentSource;\n}\n\nexport interface BraintreeFastlaneVaultedInstrument {\n id: string; // This is the nonce / token\n paymentSource: BraintreeFastlanePaymentSource;\n}\n\nexport interface BraintreeFastlaneCardComponentOptions {\n styles: BraintreeFastlaneStylesOption;\n fields: BraintreeFastlaneCardComponentFields;\n}\n\nexport interface BraintreeFastlaneCardComponentFields {\n cardholderName?: {\n enabled?: boolean;\n prefill?: string;\n };\n phoneNumber?: {\n placeholder?: string;\n prefill?: string;\n };\n}\n\nexport interface FastlaneStylesSettings {\n fastlaneRootSettingsBackgroundColor?: string;\n fastlaneRootSettingsErrorColor?: string;\n fastlaneRootSettingsFontFamily?: string;\n fastlaneRootSettingsPadding?: string;\n fastlaneRootSettingsPrimaryColor?: string;\n fastlaneRootSettingsFontSize?: string;\n fastlaneInputSettingsBackgroundColor?: string;\n fastlaneInputSettingsBorderRadius?: string;\n fastlaneInputSettingsBorderWidth?: string;\n fastlaneInputSettingsBorderColor?: string;\n fastlaneInputSettingsFocusBorderBase?: string;\n fastlaneInputSettingsTextColorBase?: string;\n fastlaneToggleSettingsColorPrimary?: string;\n fastlaneToggleSettingsColorSecondary?: string;\n fastlaneTextBodySettingsColor?: string;\n fastlaneTextBodySettingsFontSize?: string;\n fastlaneTextCaptionSettingsFontSize?: string;\n fastlaneTextCaptionSettingsColor?: string;\n fastlaneBrandingSettings?: string;\n}\n\nexport interface BraintreeFastlaneTokenizeOptions {\n name?: {\n fullName: string;\n };\n billingAddress?: BraintreeFastlaneAddress;\n shippingAddress?: BraintreeFastlaneAddress;\n}\n\nexport interface BraintreeFastlaneEvents {\n apmSelected: (options: BraintreeFastlaneApmSelectedEventOptions) => void;\n emailSubmitted: (options: BraintreeFastlaneEmailEnteredEventOptions) => void;\n orderPlaced: (options: BraintreeFastlaneOrderPlacedEventOptions) => void;\n}\n\nexport interface BraintreeFastlaneEventCommonOptions {\n context_type: 'cs_id';\n context_id: string; // checkout session id\n page_type: 'checkout_page';\n page_name: string; // title of the checkout initiation page\n partner_name: 'bigc';\n user_type: 'store_member' | 'store_guest'; // type of the user on the merchant site\n store_id: string;\n merchant_name: string;\n experiment: string; // stringify JSON object \"[{ treatment_group: 'test' | 'control' }]\"\n}\n\nexport interface BraintreeFastlaneApmSelectedEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page\n apm_selected: string; // alternate payment method selected / methodId\n apm_location: 'pre-email section' | 'payment section'; // placement of APM, whether it be above the email entry or in the radio buttons\n}\n\nexport interface BraintreeFastlaneEmailEnteredEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n user_email_saved: boolean; // shows whether checkout was loaded with or without a saved email\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page 'applepay,googlepay,paypal'\n}\n\nexport interface BraintreeFastlaneOrderPlacedEventOptions\n extends BraintreeFastlaneEventCommonOptions {\n selected_payment_method: string;\n currency_code: string;\n}\n\nexport interface BraintreeFastlaneCardComponent {\n (options: BraintreeFastlaneCardComponentOptions): BraintreeFastlaneCardComponent;\n getPaymentToken(\n options: BraintreeFastlaneTokenizeOptions,\n ): Promise;\n render(element: string): void;\n}\n\n/**\n *\n * Braintree Payload Verification\n *\n */\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\n/**\n *\n * Braintree Errors\n *\n */\nexport enum BraintreeErrorType {\n Customer = 'CUSTOMER',\n Merchant = 'MERCHANT',\n Network = 'NETWORK',\n Internal = 'INTERNAL',\n Unknown = 'UNKNOWN',\n}\n\nexport enum BraintreeErrorCode {\n KountNotEnabled = 'DATA_COLLECTOR_KOUNT_NOT_ENABLED',\n}\n\nexport interface BraintreeError extends Error {\n type: BraintreeErrorType;\n code: string | BraintreeErrorCode.KountNotEnabled;\n details?: unknown;\n}\n\n/**\n *\n * Braintree non-instant payment methods\n *\n */\n\nexport enum NonInstantLocalPaymentMethods {\n TRUSTLY = 'trustly',\n}\n\nexport interface BraintreeLocalPaymentMethodRedirectAction {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport interface BraintreeRedirectError {\n body: {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n };\n };\n}\n\nexport interface BraintreeOrderSavedResponse {\n body: {\n additional_action_required: {\n data: {\n order_id_saved_successfully: string;\n };\n };\n };\n}\n","import { BraintreeError } from '../types';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return Boolean(\n typeof error === 'object' &&\n error !== null &&\n ('type' in error || 'message' in error || 'code' in error),\n );\n}\n","import {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig,\n BraintreeError,\n BraintreeErrorCode,\n BraintreeGooglePayment,\n BraintreeLocalPayment,\n BraintreeModule,\n BraintreeThreeDSecure,\n BraintreeUsBankAccount,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\nimport { VisaCheckoutSDK } from './visacheckout';\n\nexport default class BraintreeSdk {\n private braintreeVenmo?: BraintreeVenmoCheckout;\n private braintreeLocalPayment?: BraintreeLocalPayment;\n private client?: BraintreeClient;\n private clientToken?: string;\n private dataCollector?: BraintreeDataCollector;\n private googlePayment?: BraintreeGooglePayment;\n private threeDS?: BraintreeThreeDSecure;\n private visaCheckout?: Promise;\n private visaCheckoutSDK?: VisaCheckoutSDK;\n private usBankAccount?: BraintreeUsBankAccount;\n\n constructor(private braintreeScriptLoader: BraintreeScriptLoader) {}\n\n initialize(clientToken: string): void {\n this.setClientToken(clientToken);\n }\n\n async deinitialize(): Promise {\n await this.teardownModule(this.dataCollector);\n\n this.dataCollector = undefined;\n }\n\n /**\n *\n * Braintree Client\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_client.html\n *\n */\n async getClient(): Promise {\n if (!this.client) {\n const clientToken = this.getClientTokenOrThrow();\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = await clientCreator.create({ authorization: clientToken });\n }\n\n return this.client;\n }\n\n /**\n *\n * Braintree Data collector\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_data-collector.html\n *\n */\n async getDataCollectorOrThrow(\n options?: Partial,\n ): Promise {\n const emptyDataCollector = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n\n if (!this.dataCollector) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n const dataCollectorConfig: BraintreeDataCollectorCreatorConfig = {\n client,\n kount: true,\n ...options,\n };\n\n this.dataCollector = await dataCollector.create(dataCollectorConfig);\n } catch (error) {\n if (isBraintreeError(error) && error.code === BraintreeErrorCode.KountNotEnabled) {\n return emptyDataCollector;\n }\n\n throw error;\n }\n }\n\n return this.dataCollector;\n }\n\n /**\n *\n * Braintree Google Payment\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_google-payment.html\n *\n */\n async getBraintreeGooglePayment(): Promise {\n if (!this.googlePayment) {\n const [client, braintreeGooglePayment] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadGooglePayment(),\n ]);\n\n this.googlePayment = await braintreeGooglePayment.create({ client });\n }\n\n return this.googlePayment;\n }\n\n /**\n *\n * Braintree 3DS\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_three-d-secure.html\n *\n */\n async getBraintreeThreeDS(): Promise {\n if (!this.threeDS) {\n const [client, threeDSecure] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.load3DS(),\n ]);\n\n this.threeDS = await threeDSecure.create({ client, version: 2 });\n }\n\n return this.threeDS;\n }\n\n /**\n *\n * Braintree Local Payment Methods\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_local-payment.html\n *\n */\n async getBraintreeLocalPayment(\n merchantAccountId: string,\n ): Promise {\n if (!this.braintreeLocalPayment) {\n const [client, localPaymentCreator] = await Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadLocalPayment(),\n ]);\n\n this.braintreeLocalPayment = await new Promise(\n (\n resolve: (braintreeLocalPayment: BraintreeLocalPayment) => void,\n reject: (error: BraintreeError) => void,\n ) => {\n void localPaymentCreator.create(\n { client, merchantAccountId },\n (\n error: BraintreeError | undefined,\n braintreeLocalPayment: BraintreeLocalPayment,\n ) => {\n if (error) {\n reject(error);\n }\n\n resolve(braintreeLocalPayment);\n },\n );\n },\n );\n }\n\n return this.braintreeLocalPayment;\n }\n\n /**\n *\n * Braintree UsBankAccount\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_us-bank-account.html\n *\n */\n async getUsBankAccount() {\n if (!this.usBankAccount) {\n const client = await this.getClient();\n const usBankAccount = await this.braintreeScriptLoader.loadUsBankAccount();\n\n this.usBankAccount = await usBankAccount.create({ client });\n }\n\n return this.usBankAccount;\n }\n\n /**\n *\n * Braintree Visa Checkout\n * braintree doc: https://braintree.github.io/braintree-web/current/module-braintree-web_visa-checkout.html\n *\n */\n getBraintreeVisaCheckout() {\n if (!this.visaCheckout) {\n this.visaCheckout = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this.visaCheckout;\n }\n\n /**\n *\n * Braintree Visa Checkout SDK\n * visa checkout doc: https://developer.visa.com/capabilities/visa_checkout/docs-how-to\n *\n */\n async getVisaCheckoutSdk(testMode?: boolean) {\n if (!this.visaCheckoutSDK) {\n this.visaCheckoutSDK = await this.braintreeScriptLoader.loadVisaCheckoutSdk(testMode);\n }\n\n return this.visaCheckoutSDK;\n }\n\n /**\n *\n * Braintree Venmo Checkout\n * braintree venmo checkout doc: https://braintree.github.io/braintree-web/current/module-braintree-web_venmo.html\n *\n */\n async getVenmoCheckoutOrThrow() {\n if (!this.braintreeVenmo) {\n const client = await this.getClient();\n const venmoCheckout = await this.braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const braintreeVenmoCheckout = await venmoCheckout.create(venmoCheckoutConfig);\n\n if (braintreeVenmoCheckout.isBrowserSupported()) {\n this.braintreeVenmo = braintreeVenmoCheckout;\n } else {\n throw new UnsupportedBrowserError();\n }\n }\n\n return this.braintreeVenmo;\n }\n\n /**\n *\n * Private methods\n *\n */\n private setClientToken(clientToken: string): void {\n this.clientToken = clientToken;\n }\n\n private getClientTokenOrThrow(): string {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.clientToken;\n }\n\n private teardownModule(module?: BraintreeModule): Promise {\n return module ? module.teardown() : Promise.resolve();\n }\n}\n","import { Omit } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PaypalAuthorizeData,\n PaypalButtonOptions,\n PaypalButtonRender,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal';\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeError,\n BraintreeFastlaneCreator,\n BraintreeGooglePaymentCreator,\n BraintreeHostedFieldsTokenizePayload,\n BraintreeModule,\n BraintreeModuleCreator,\n BraintreeModuleCreatorConfig,\n BraintreeThreeDSecureCreator,\n BraintreeTokenizationDetails,\n BraintreeUsBankAccountCreator,\n BraintreeWindow,\n FastlaneStylesSettings,\n VisaCheckoutSDK,\n} from './types';\nimport {\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\n/**\n *\n * Constants\n *\n */\nexport enum BraintreeEnv {\n Sandbox = 'sandbox',\n Production = 'production',\n}\n\n/**\n *\n * Common\n *\n */\nexport enum BraintreeModuleName {\n Client = 'client',\n DataCollector = 'dataCollector',\n Fastlane = 'fastlane',\n GooglePayment = 'googlePayment',\n HostedFields = 'hostedFields',\n LocalPayment = 'localPayment',\n Paypal = 'paypal',\n PaypalCheckout = 'paypalCheckout',\n ThreeDSecure = 'threeDSecure',\n UsBankAccount = 'usBankAccount',\n Venmo = 'venmo',\n VisaCheckout = 'visaCheckout',\n}\n\nexport type BraintreeModuleCreators =\n | BraintreeClientCreator\n | BraintreeFastlaneCreator\n | BraintreeDataCollectorCreator\n | BraintreeGooglePaymentCreator\n | BraintreeHostedFieldsCreator\n | BraintreePaypalCreator\n | BraintreePaypalCheckoutCreator\n | BraintreeThreeDSecureCreator\n | BraintreeVenmoCheckoutCreator\n | BraintreeVisaCheckoutCreator\n | BraintreeUsBankAccountCreator\n | BraintreeLocalPaymentCreator;\n\n// TODO: rename to BraintreeSdkModules\nexport interface BraintreeSDK {\n [BraintreeModuleName.Client]?: BraintreeClientCreator;\n [BraintreeModuleName.Fastlane]?: BraintreeFastlaneCreator;\n [BraintreeModuleName.DataCollector]?: BraintreeDataCollectorCreator;\n [BraintreeModuleName.GooglePayment]?: BraintreeGooglePaymentCreator;\n [BraintreeModuleName.HostedFields]?: BraintreeHostedFieldsCreator;\n [BraintreeModuleName.Paypal]?: BraintreePaypalCreator;\n [BraintreeModuleName.PaypalCheckout]?: BraintreePaypalCheckoutCreator;\n [BraintreeModuleName.ThreeDSecure]?: BraintreeThreeDSecureCreator;\n [BraintreeModuleName.Venmo]?: BraintreeVenmoCheckoutCreator;\n [BraintreeModuleName.VisaCheckout]?: BraintreeVisaCheckoutCreator;\n [BraintreeModuleName.UsBankAccount]?: BraintreeUsBankAccountCreator;\n [BraintreeModuleName.LocalPayment]?: BraintreeLocalPaymentCreator;\n}\n\nexport type BraintreeLocalPaymentCreator = BraintreeModuleCreator<\n BraintreeLocalPayment,\n BraintreeLocalPaymentCreateConfig,\n BraintreeError | undefined\n>;\n\nexport interface BraintreeLocalPaymentCreateConfig extends BraintreeModuleCreatorConfig {\n merchantAccountId: string;\n}\n\nexport interface BraintreeInitializationData {\n clientToken: string;\n intent?: 'authorize' | 'order' | 'sale';\n isCreditEnabled?: boolean;\n isAcceleratedCheckoutEnabled?: boolean;\n isFastlaneStylingEnabled?: boolean;\n isFastlaneEnabled?: boolean;\n isFastlaneShippingOptionAutoSelectEnabled?: boolean;\n fastlaneStyles?: FastlaneStylesSettings;\n isBraintreeAnalyticsV2Enabled?: boolean;\n shouldRunAcceleratedCheckout?: boolean; // TODO: only for BT AXO A/B testing purposes, hence should be removed after testing\n paymentButtonStyles?: Record;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeTokenizationDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport type BraintreeFormErrorData = Omit;\n\nexport type BraintreeFormErrorDataKeys =\n | 'number'\n | 'expirationDate'\n | 'expirationMonth'\n | 'expirationYear'\n | 'cvv'\n | 'postalCode';\n\nexport type BraintreeFormErrorsData = Partial<\n Record\n>;\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n getState(): BraintreeHostedFieldsState;\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n cardholderName?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\nexport interface BraintreeFormFieldState {\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface TokenizationPayload {\n nonce: string;\n bin: string;\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\n// export interface BraintreeThreeDSecureOptions {\n// /**\n// * A callback that gets called when the iframe is ready to be added to the\n// * current page. It is responsible for determining where the iframe should\n// * be inserted in the DOM.\n// *\n// * @param error - Any error raised during the verification process;\n// * undefined if there is none.\n// * @param iframe - The iframe element containing the verification web page\n// * provided by the card issuer.\n// * @param cancel - A function, when called, will cancel the verification\n// * process and remove the iframe.\n// */\n// addFrame(\n// error: Error | undefined,\n// iframe: HTMLIFrameElement,\n// cancel: () => Promise | undefined,\n// ): void;\n//\n// /**\n// * A callback that gets called when the iframe is about to be removed from\n// * the current page.\n// */\n// removeFrame(): void;\n// }\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n commit?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => unknown): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\nexport type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreeVisaCheckout extends BraintreeModule {\n tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n createInitOptions(options: Partial): VisaCheckoutInitOptions;\n}\n\n/**\n *\n * Braintree Local Methods\n *\n */\nexport interface BraintreeLocalPaymentConfig {\n paymentType: string;\n amount: number;\n fallback: {\n url: string;\n buttonText: string;\n };\n currencyCode: string;\n shippingAddressRequired: boolean;\n email: string;\n givenName: string;\n surname: string;\n address: {\n countryCode: string;\n };\n onPaymentStart(data: BraintreeLPMPaymentStartData, start: () => Promise): Promise;\n}\n\nexport interface BraintreeLPMStartPaymentError {\n code: string;\n}\n\nexport interface BraintreeLPMPaymentStartData {\n paymentId: string;\n}\n\nexport interface BraintreeLocalPaymentsPayload {\n nonce: string;\n}\n\nexport interface BraintreeLocalPayment extends BraintreeModule {\n startPayment(\n config: BraintreeLocalPaymentConfig,\n callback: (\n startPaymentError: BraintreeLPMStartPaymentError | undefined,\n payload: BraintreeLocalPaymentsPayload,\n ) => Promise,\n ): void;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends BraintreeWindow {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n V?: VisaCheckoutSDK;\n}\n","import { BraintreeModuleName } from './braintree';\n\nexport const BRAINTREE_SDK_SCRIPTS_INTEGRITY = {\n [BraintreeModuleName.Client]:\n 'sha384-26BXDNnJI23JYRyFBj4xe4sVNrUSSiSSu11kxVXNM/vEPONm4LuL00w6ZaTgQewt',\n [BraintreeModuleName.PaypalCheckout]:\n 'sha384-B+vzbZwnQtzWBthpkT4TXKUibO65tyeK7eCxSvpblgprTep2+IAXB2Cxxjrn710O',\n [BraintreeModuleName.Paypal]:\n 'sha384-uyAGL1/3+XJAHnGoNy4eCoXdzJ4f7Ilzp+6w9PNnEjs6DCCz9WMyJjMN1gzc78U+',\n [BraintreeModuleName.LocalPayment]:\n 'sha384-LIvOEMkIVEwVuYBdVOQc1AC5YbGGlwyfUheS0ACK218D2STuVYQlZ4FyEPowAEfT',\n [BraintreeModuleName.DataCollector]:\n 'sha384-1bo9JDz+Kscthc085cCKWur8CLwUoBpoNyxsDi7932mCl0zFq3A5mv+FQLw9GHpV',\n [BraintreeModuleName.UsBankAccount]:\n 'sha384-xmHBVaU+w74V+OebD3AaPONFxHUGMf+QRs8G/JxVPXNNP7MDa2jL0ICWHIe2tTfJ',\n [BraintreeModuleName.GooglePayment]:\n 'sha384-WKDJl8mqoP82qZpMGH6AbZxnvXnSW8ILV4M64CyMLiugGMwu7LyP89wjCkHqsiBe',\n [BraintreeModuleName.ThreeDSecure]:\n 'sha384-VQUlpGHzsGvs5XeiGFip7EXRsvoHWEXDVmgCacfbyieZI9mdBOqq3NSoyo28OCOB',\n [BraintreeModuleName.VisaCheckout]:\n 'sha384-yx7mADfzTN0T43Q6rlH49LIg1EJ0iUZgBp/EczX9LXsUGkySgxrD+nWHQRBkyfoT',\n [BraintreeModuleName.Venmo]:\n 'sha384-QX4rPjoj1ZDhuG0aSyKs56lEKDqTMTcjYxUHY1SzO5VZDsqIE2NTkqot7KNSCyov',\n [BraintreeModuleName.HostedFields]:\n 'sha384-VvYBACfSu0Cr/J32uKmxG7AXcNOJE1AzIIL3kbikyS7YKp5fz5Is+NzNP/lyauNy',\n [BraintreeModuleName.Fastlane]:\n 'sha384-9oGsZMRZwpGtDEDYa/dFt76dECqj1xAni9gIKgc3KfMIiRnR73nEeeUDLiBzxhFa',\n};\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BRAINTREE_SDK_SCRIPTS_INTEGRITY } from './braintree-sdk-scripts-integrity';\nimport { BRAINTREE_SDK_STABLE_VERSION } from './braintree-sdk-verison';\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeFastlaneCreator,\n BraintreeGooglePaymentCreator,\n BraintreeHostedFieldsCreator,\n BraintreeHostWindow,\n BraintreeLocalPaymentCreator,\n BraintreeModuleCreators,\n BraintreeModuleName,\n BraintreePaypalCheckoutCreator,\n BraintreePaypalCreator,\n BraintreeThreeDSecureCreator,\n BraintreeUsBankAccountCreator,\n BraintreeVenmoCheckoutCreator,\n BraintreeVisaCheckoutCreator,\n} from './types';\nimport { VisaCheckoutSDK } from './visacheckout';\n\nexport default class BraintreeScriptLoader {\n private braintreeSdkVersion = BRAINTREE_SDK_STABLE_VERSION;\n\n constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async loadClient(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Client,\n 'client.min.js',\n );\n }\n\n async loadFastlane(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Fastlane,\n 'fastlane.min.js',\n );\n }\n\n async loadPaypalCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.PaypalCheckout,\n 'paypal-checkout.min.js',\n );\n }\n\n async loadPaypal(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Paypal,\n 'paypal.min.js',\n );\n }\n\n async loadLocalPayment(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.LocalPayment,\n 'local-payment.min.js',\n );\n }\n\n async loadDataCollector(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.DataCollector,\n 'data-collector.min.js',\n );\n }\n\n async loadUsBankAccount(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.UsBankAccount,\n 'us-bank-account.min.js',\n );\n }\n\n async loadGooglePayment(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.GooglePayment,\n 'google-payment.min.js',\n );\n }\n\n async load3DS(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.ThreeDSecure,\n 'three-d-secure.min.js',\n );\n }\n\n loadVisaCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.VisaCheckout,\n 'visa-checkout.min.js',\n );\n }\n\n loadVenmoCheckout(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.Venmo,\n 'venmo.min.js',\n );\n }\n\n async loadHostedFields(): Promise {\n return this.loadBraintreeModuleOrThrow(\n BraintreeModuleName.HostedFields,\n 'hosted-fields.min.js',\n );\n }\n\n async loadVisaCheckoutSdk(testMode?: boolean): Promise {\n if (this.braintreeHostWindow.V) {\n return this.braintreeHostWindow.V;\n }\n\n const hash = testMode\n ? 'sha384-0eu1s1GtqzXlL9DtLgmwzC5WWlEH/ADRM0n38cVQkvtT+W/gey96rcb1LwuUOPDm'\n : 'sha384-1f1csvP3ZFxg4dILH1GaY4LHlZ0oX7Rk83rxmLlwbnIi4TM0NYzXoev1VoEiVDS6';\n\n return this.scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n {\n async: true,\n attributes: {\n integrity: hash,\n crossorigin: 'anonymous',\n },\n },\n )\n .then(() => {\n if (!this.braintreeHostWindow.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.V;\n });\n }\n\n private async loadBraintreeModuleOrThrow(\n braintreeModuleName: BraintreeModuleName,\n fileName: string,\n ): Promise {\n let module = this.getBraintreeModule(braintreeModuleName);\n\n if (module) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return module as T;\n }\n\n const scriptPath = `//js.braintreegateway.com/web/${this.braintreeSdkVersion}/js/${fileName}`;\n\n const integrity = this.getIntegrityValuesByModuleName(braintreeModuleName);\n\n await this.scriptLoader.loadScript(\n scriptPath,\n integrity\n ? {\n async: true,\n attributes: {\n integrity,\n crossorigin: 'anonymous',\n },\n }\n : undefined,\n );\n\n module = this.getBraintreeModule(braintreeModuleName);\n\n if (!module) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return module as T;\n }\n\n private getBraintreeModule(\n braintreeModuleName: BraintreeModuleName,\n ): BraintreeModuleCreators | undefined {\n return this.braintreeHostWindow.braintree?.[braintreeModuleName];\n }\n\n private getIntegrityValuesByModuleName(moduleName: BraintreeModuleName): string {\n const integrity = BRAINTREE_SDK_SCRIPTS_INTEGRITY[moduleName];\n\n if (!integrity) {\n throw new Error('Unexpected fileName value');\n }\n\n return integrity;\n }\n}\n","export const BRAINTREE_SDK_STABLE_VERSION = '3.106.0';\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","export enum ApplePayGatewayType {\n BRAINTREE = 'braintree',\n BRAINTREE_FASTLANE = 'braintreeacceleratedcheckout',\n}\n","interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nfunction isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n\nexport default class ApplePaySessionFactory {\n create(request: ApplePayJS.ApplePayPaymentRequest): ApplePaySession {\n assertApplePayWindow(window);\n\n return new ApplePaySession(1, request);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n AddressRequestBody,\n Cart,\n Checkout,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport { WithApplePayCustomerInitializeOptions } from './apple-pay-customer-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _onAuthorizeCallback = noop;\n private _onError = noop;\n private _onClick = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _hasApplePaySession = false;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n container,\n shippingLabel,\n subtotalLabel,\n onError = noop,\n onClick = noop,\n onPaymentAuthorize,\n } = applepay;\n\n this._shippingLabel = shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = subtotalLabel || DefaultLabels.Subtotal;\n this._onAuthorizeCallback = onPaymentAuthorize;\n this._onError = onError;\n this._onClick = onClick;\n\n let state = this._paymentIntegrationService.getState();\n\n try {\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(methodId);\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(container);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n if (this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Apple, the shopper must click on \"Apple Pay\" button.',\n );\n }\n\n signOut(): Promise {\n throw new NotImplementedError('Need to do signout via apple.');\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private _createButton(containerId: string): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('button');\n\n button.setAttribute('type', 'button');\n button.setAttribute('aria-label', 'Apple Pay');\n container.appendChild(button);\n\n return button;\n }\n\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (this._hasApplePaySession) {\n return;\n }\n\n this._onClick();\n\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, config);\n\n applePaySession.begin();\n this._hasApplePaySession = true;\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n config: StoreConfig,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n this._onError(err);\n }\n };\n\n applePaySession.onshippingcontactselected = async (event) =>\n this._handleShippingContactSelected(applePaySession, config, event);\n\n applePaySession.onshippingmethodselected = async (event) =>\n this._handleShippingMethodSelected(applePaySession, config, event);\n\n applePaySession.oncancel = async () => {\n this._hasApplePaySession = false;\n\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n return this._onError(new PaymentMethodCancelledError());\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n this._hasApplePaySession = false;\n\n return this._onError(error);\n }\n\n const {\n storeProfile: { storeName },\n } = config;\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n return this._onError(error);\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n storeProfile: { storeName },\n } = config;\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n this._hasApplePaySession = false;\n\n return this._onError(error);\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return this._onError(error);\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n const state = this._paymentIntegrationService.getState();\n const braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayCustomerStrategy from './apple-pay-customer-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayCustomerStrategy, [{ id: 'applepay' }]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a payment method experiences some kind of\n * failure (i.e.: its client library returns a rejected promise). And there is\n * no other error type that is more specific than this one.\n */\nexport default class PaymentMethodFailedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method has thrown an unexpected error.',\n );\n\n this.name = 'PaymentMethodFailedError';\n this.type = 'payment_method_client_invalid';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if we are unable to successfully submit a server request\n * using a payment method because the method has invalid configuration or is in\n * an invalid state.\n */\nexport default class PaymentMethodInvalidError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'There is a problem processing your payment. Please try again later.',\n });\n\n this.name = 'PaymentMethodInvalidError';\n this.type = 'payment_method_invalid';\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n CheckoutPaymentMethodExecutedOptions,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n isCustomError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltCheckout, BoltHostWindow, BoltInitializationData } from './bolt';\nimport { WithBoltCustomerInitializeOptions } from './bolt-customer-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltCustomerStrategy implements CustomerStrategy {\n private boltHostWindow: BoltHostWindow = window;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBoltCustomerInitializeOptions,\n ): Promise {\n const { methodId, bolt } = options;\n const { onInit } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData?.publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { developerConfig, publishableKey } = paymentMethod.initializationData;\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n paymentMethod.config.testMode,\n developerConfig,\n );\n\n if (onInit && typeof onInit === 'function') {\n const email = this.getCustomerEmail();\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n onInit(hasBoltAccount, email);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const {\n continueWithCheckoutCallback = noop,\n checkoutPaymentMethodExecuted,\n methodId,\n } = options || {};\n const email = this.getCustomerEmail();\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n if (!email) {\n continueWithCheckoutCallback();\n\n return;\n }\n\n return this.openBoltCheckoutModalOrThrow(\n email,\n methodId,\n continueWithCheckoutCallback,\n checkoutPaymentMethodExecuted,\n );\n }\n\n private async openBoltCheckoutModalOrThrow(\n email: string,\n methodId: string,\n continueWithCheckoutCallback: () => void,\n checkoutPaymentMethodExecuted?: (payload: CheckoutPaymentMethodExecutedOptions) => void,\n ): Promise {\n const boltClient = this.getBoltClientOrThrow();\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n try {\n if (paymentMethod?.initializationData?.embeddedOneClickEnabled) {\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n if (hasBoltAccount) {\n const callbacks = {\n close: () => {\n continueWithCheckoutCallback();\n },\n };\n\n await boltClient.openCheckout(email, callbacks);\n } else {\n continueWithCheckoutCallback();\n }\n\n if (typeof checkoutPaymentMethodExecuted === 'function') {\n checkoutPaymentMethodExecuted({ hasBoltAccount });\n }\n } else {\n continueWithCheckoutCallback();\n }\n } catch (error) {\n if (\n isCustomError(error) &&\n error.name !== 'MissingDataError' &&\n error.name !== 'NotInitializedError'\n ) {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n const boltClient = this.boltHostWindow.BoltCheckout;\n\n if (!boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return boltClient;\n }\n\n private async hasBoltAccount(email: string) {\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private getCustomerEmail() {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n\n return customer?.email || billingAddress?.email || '';\n }\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: any): error is CustomError {\n return (\n typeof error.message === 'string' &&\n typeof error.type === 'string' &&\n (typeof error.subtype === 'string' || !error.subtype) &&\n error instanceof Error\n );\n}\n","import {\n BuyNowCartRequestBody,\n NonceInstrument,\n PaymentMethod,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface BoltHostWindow extends Window {\n BoltCheckout?: BoltCheckout;\n BoltConnect?: BoltConnect;\n Bolt?(publicKey: string): BoltEmbedded;\n}\n\nexport interface BoltCheckout {\n configure(cart: BoltCart, hints: Record, callbacks?: BoltCallbacks): BoltClient;\n hasBoltAccount(email: string): Promise;\n getTransactionReference(): Promise;\n openCheckout(email: string, callbacks?: BoltOpenCheckoutCallbacks): Promise;\n setClientCustomCallbacks(callbacks: BoltCallbacks): void;\n setOrderId(orderId: number): Promise;\n}\n\nexport interface BoltConnect {\n setupProductPageCheckout?(): void;\n}\n\nexport interface BoltOpenCheckoutCallbacks {\n close?(): void;\n}\n\nexport interface BoltEmbeddedOptions {\n styles: { backgroundColor: string };\n renderSeparateFields?: boolean;\n}\n\nexport interface BoltEmbedded {\n create(name: string, options?: BoltEmbeddedOptions): BoltEmbededField;\n}\n\nexport interface BoltEmbededField {\n mount(element: string): void;\n unmount(): void;\n tokenize(): Promise;\n}\n\nexport interface BoltDeveloperModeParams {\n developerMode: BoltDeveloperMode;\n developerDomain: string;\n}\n\nexport enum BoltDeveloperMode {\n SandboxMode = 'bolt_sandbox',\n StagingMode = 'bolt_staging',\n DevelopmentMode = 'bolt_development',\n}\n\nexport interface BoltClient {\n open(): void;\n}\n\nexport interface BoltCart {\n orderToken: string;\n}\n\nexport interface BoltCallbacks {\n check?(): boolean;\n onCheckoutStart?(): void;\n onPaymentSubmit?(): void;\n success(transaction: BoltTransaction, callback: () => void): void;\n close?(): void;\n}\n\nexport interface BoltTransaction {\n id: string;\n type: string;\n processor: string;\n date: number;\n reference: string;\n status: string;\n authorization: BoltAuthorization;\n}\n\nexport interface BoltAuthorization {\n status: string;\n reason: string;\n}\n\nexport interface BoltEmbeddedTokenize {\n bin: string;\n expiration: string;\n last4: string;\n postal_code?: string;\n token: string;\n token_type: string;\n}\n\nexport interface BoltPaymentMethod extends PaymentMethod {\n initializationData?: BoltInitializationData;\n}\n\nexport interface BoltInitializationData {\n publishableKey: string;\n developerConfig: BoltDeveloperModeParams;\n embeddedOneClickEnabled: boolean;\n}\n\nexport type BoltPaymentData = WithAccountCreation & NonceInstrument;\n\nexport interface BoltBuyNowInitializeOptions {\n storefrontApiToken?: string;\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\nexport enum StyleButtonSize {\n Small = 'small',\n Medium = 'medium',\n Large = 'large',\n}\n\nexport enum StyleButtonShape {\n Pill = 'pill',\n Rect = 'rect',\n}\n\nexport interface BoltButtonStyleOptions {\n shape?: StyleButtonShape;\n size?: StyleButtonSize;\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n InvalidArgumentError,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltDeveloperMode,\n BoltDeveloperModeParams,\n BoltEmbedded,\n BoltHostWindow,\n} from './bolt';\n\nexport default class BoltScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async loadBoltClient(\n publishableKey?: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n cartId?: string,\n storefrontApiToken?: string,\n ): Promise {\n if (this.boltHostWindow.BoltCheckout) {\n return this.boltHostWindow.BoltCheckout;\n }\n\n if (!publishableKey) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publishableKey\" argument is not provided.',\n );\n }\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/connect-bigcommerce.js`,\n this.getScriptOptions('bolt-connect', publishableKey, cartId, storefrontApiToken),\n );\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/track.js`,\n this.getScriptOptions('bolt-track', publishableKey),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this.boltHostWindow.BoltCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.BoltCheckout;\n }\n\n async loadBoltEmbedded(\n publishableKey: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n ): Promise {\n const options: LoadScriptOptions = {\n async: true,\n attributes: {\n id: 'bolt-embedded',\n },\n };\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/embed.js`,\n options,\n );\n\n if (!this.boltHostWindow.Bolt) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.Bolt(publishableKey);\n }\n\n getDomainURL(testMode: boolean, developerModeParams?: BoltDeveloperModeParams): string {\n if (!testMode) {\n return 'connect.bolt.com';\n }\n\n if (developerModeParams) {\n switch (developerModeParams.developerMode) {\n case BoltDeveloperMode.StagingMode:\n return 'connect-staging.bolt.com';\n\n case BoltDeveloperMode.DevelopmentMode:\n return `connect.${developerModeParams.developerDomain}`;\n }\n }\n\n return 'connect-sandbox.bolt.com';\n }\n\n private getScriptOptions(\n id: string,\n publishableKey: string,\n cartId?: string,\n storefrontApiToken?: string,\n ): LoadScriptOptions {\n return {\n async: true,\n attributes: {\n id,\n 'data-publishable-key': publishableKey,\n ...(cartId && { 'data-shopping-cart-id': cartId }),\n ...(storefrontApiToken && { 'data-storefront-api-token': storefrontApiToken }),\n },\n };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltCustomerStrategy from './bolt-customer-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltCustomerStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltCustomerStrategy, [{ id: 'bolt' }]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/form-poster\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@braintree/browser-detection\");","// the PayPal side of things uses uppercase keys instead of camel case\n\n/**\n *\n * PayPal constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n WHITE = 'white',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\n/**\n *\n * PayPal interfaces\n *\n */\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface MessagingOptions {\n amount: number;\n buyerCountry?: string;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface MessagesStyleOptions {\n layout?: 'text' | 'flex';\n logo?: {\n type: 'none' | 'inline' | 'primary';\n };\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onClick?(): void;\n onCancel?(): void;\n onError?(error: Error): void;\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n close(): void;\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n","import { supportsPopups } from '@braintree/browser-detection';\n\nimport {\n Address,\n LegacyAddress,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig,\n BraintreeDataCollectors,\n BraintreeEnv,\n BraintreeError,\n BraintreeFastlane,\n BraintreeFastlaneStylesOption,\n BraintreeHostWindow,\n BraintreeModule,\n BraintreePaypal,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeShippingAddressOverride,\n BraintreeTokenizationDetails,\n BraintreeTokenizePayload,\n PAYPAL_COMPONENTS,\n} from './types';\nimport isBraintreeError from './utils/is-braintree-error';\n\nexport interface PaypalConfig {\n amount: number;\n currency: string;\n locale: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n shouldSaveInstrument?: boolean;\n}\n\n// Info: this class is deprecated and will be removed in a nearest future. Please, do not add anything here.\nexport default class BraintreeIntegrationService {\n private client?: Promise;\n private clientToken?: string;\n private dataCollectors: BraintreeDataCollectors = {};\n private paypalCheckout?: BraintreePaypalCheckout;\n private braintreePaypal?: Promise;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n private overlay?: Overlay,\n ) {}\n\n initialize(clientToken: string) {\n this.clientToken = clientToken;\n }\n\n async getBraintreeFastlane(\n cardId?: string,\n isTestModeEnabled?: boolean,\n styles?: BraintreeFastlaneStylesOption,\n ): Promise {\n if (isTestModeEnabled) {\n window.localStorage.setItem('axoEnv', 'sandbox');\n window.localStorage.setItem('fastlaneEnv', 'sandbox');\n }\n\n if (!this.braintreeHostWindow.braintreeFastlane) {\n const clientToken = this.getClientTokenOrThrow();\n const client = await this.getClient();\n const deviceData = await this.getSessionId(cardId);\n\n const braintreeFastlaneCreator = await this.braintreeScriptLoader.loadFastlane();\n\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.braintreeHostWindow.braintreeFastlane = await braintreeFastlaneCreator.create({\n authorization: clientToken,\n client,\n deviceData,\n styles: styles || defaultStyles,\n });\n }\n\n return this.braintreeHostWindow.braintreeFastlane;\n }\n\n // Info: This method is deprecated. Use getClient method from BraintreeSdk class instead\n async getClient(): Promise {\n if (!this.client) {\n const clientToken = this.getClientTokenOrThrow();\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = clientCreator.create({ authorization: clientToken });\n }\n\n return this.client;\n }\n\n getPaypal(): Promise {\n if (!this.braintreePaypal) {\n this.braintreePaypal = Promise.all([\n this.getClient(),\n this.braintreeScriptLoader.loadPaypal(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this.braintreePaypal;\n }\n\n paypal({ shouldSaveInstrument, ...config }: PaypalConfig): Promise {\n const newWindowFlow = supportsPopups();\n\n return this.getPaypal()\n .then((paypal) => {\n if (newWindowFlow) {\n this.overlay?.show({\n onClick: () => paypal.focusWindow(),\n });\n }\n\n return paypal.tokenize({\n enableShippingAddress: true,\n flow: shouldSaveInstrument ? 'vault' : 'checkout',\n useraction: 'commit',\n ...config,\n });\n })\n .then((response) => {\n this.overlay?.remove();\n\n return response;\n })\n .catch((error) => {\n this.overlay?.remove();\n\n throw error;\n });\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this.braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError | undefined,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n commit: config.commit ?? true,\n };\n\n if (!this.braintreeHostWindow.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this.paypalCheckout = await paypalCheckout.create(\n paypalCheckoutConfig,\n paypalCheckoutCallback,\n );\n\n return this.paypalCheckout;\n }\n\n async getDataCollector(\n options?: Partial,\n ): Promise {\n const cacheKey: keyof BraintreeDataCollectors = options?.paypal ? 'paypal' : 'default';\n\n let cached = this.dataCollectors[cacheKey];\n\n if (!cached) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n const dataCollectorConfig: BraintreeDataCollectorCreatorConfig = {\n client,\n kount: true,\n ...options,\n };\n\n cached = await dataCollector.create(dataCollectorConfig);\n } catch (error) {\n if (isBraintreeError(error) && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n cached = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n } else {\n throw error;\n }\n }\n\n this.dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getBraintreeEnv(isTestMode = false): BraintreeEnv {\n return isTestMode ? BraintreeEnv.Sandbox : BraintreeEnv.Production;\n }\n\n mapToBraintreeShippingAddressOverride(address: Address): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n }\n\n mapToLegacyShippingAddress(details: BraintreeTokenizationDetails): Partial {\n const { email, phone, shippingAddress } = details;\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n }\n\n mapToLegacyBillingAddress(details: BraintreeTokenizationDetails): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n }\n\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n async getSessionId(cartId?: string): Promise {\n const { deviceData } = await this.getDataCollector({\n riskCorrelationId: cartId,\n });\n\n return deviceData;\n }\n\n async teardown(): Promise {\n await this.teardownModule(this.dataCollectors.default);\n await this.teardownModule(this.dataCollectors.paypal);\n this.dataCollectors = {};\n\n await this.teardownModule(this.paypalCheckout);\n this.paypalCheckout = undefined;\n\n // await this.teardownModule(this._venmoCheckout);\n // this._venmoCheckout = undefined;\n\n // await this.teardownModule(this._visaCheckout);\n // this._visaCheckout = undefined;\n }\n\n private teardownModule(module?: BraintreeModule) {\n return module ? module.teardown() : Promise.resolve();\n }\n\n private getClientTokenOrThrow(): string {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.clientToken;\n }\n}\n","const DefaultCheckoutButtonHeight = 36;\n\nexport default DefaultCheckoutButtonHeight;\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCustomerInitializeOptions, {\n WithBraintreePaypalCustomerInitializeOptions,\n} from './braintree-paypal-customer-initialize-options';\n\nexport default class BraintreePaypalCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypal, methodId } = options;\n const { container, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.container\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n const { clientToken, config, initializationData } = paymentMethod;\n const { paymentButtonStyles } = initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n methodId,\n Boolean(config.testMode),\n checkoutTopButtonStyles,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonStyles: PaypalStyleOptions,\n ): void {\n const { container, onClick = noop } = braintreepaypal;\n\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const paypalButtonRender = paypal.Buttons({\n env: this.braintreeIntegrationService.getBraintreeEnv(testMode),\n fundingSource,\n style: { ...buttonStyles, height: DefaultCheckoutButtonHeight },\n createOrder: () =>\n this.setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypal,\n ),\n onClick,\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n }\n } else {\n this.braintreeIntegrationService.removeElement(container);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCustomerStrategy from './braintree-paypal-customer-strategy';\n\nconst createBraintreePaypalCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCustomerStrategy, [\n { id: 'braintreepaypal' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n isBraintreeError,\n PaypalAuthorizeData,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditCustomerInitializeOptions, {\n WithBraintreePaypalCreditCustomerInitializeOptions,\n} from './braintree-paypal-credit-customer-options';\n\nexport default class BraintreePaypalCreditCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCreditCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypalcredit, methodId } = options;\n const { container, onError } = braintreepaypalcredit || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.container\" argument is not provided.`,\n );\n }\n\n let state = this.paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n } catch (_e) {\n state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n paymentMethod = state.getPaymentMethodOrThrow(methodId);\n }\n\n const { clientToken, config, initializationData } = paymentMethod;\n const { paymentButtonStyles } = initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n commit: false,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n Boolean(config.testMode),\n { ...checkoutTopButtonStyles, height: DefaultCheckoutButtonHeight },\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonStyles: PaypalStyleOptions,\n ): void {\n const { container, onClick = noop } = braintreepaypalcredit;\n const { paypal } = this.braintreeHostWindow;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: buttonStyles,\n createOrder: () =>\n this.setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypalcredit,\n ),\n onClick,\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this.braintreeIntegrationService.removeElement(container);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypalcredit;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypalcredit;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreePaypalCreditCustomerStrategy from './braintree-paypal-credit-customer-strategy';\n\nconst createBraintreePaypalCreditCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCreditCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCreditCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCreditCustomerStrategy, [\n { id: 'braintreepaypalcredit' },\n]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"local-storage-fallback\");","import LocalStorage from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = LocalStorage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return LocalStorage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return LocalStorage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this.namespace}.${key}`;\n }\n}\n","import { omitBy } from 'lodash';\n\nimport { BraintreeFastlaneStylesOption, FastlaneStylesSettings } from '../index';\n\nfunction isInvalidStyleOption(styleOption: unknown) {\n return typeof styleOption !== 'string';\n}\n\nexport default function getFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: BraintreeFastlaneStylesOption,\n): BraintreeFastlaneStylesOption | undefined {\n if (!uiStyles && !styleSettings) {\n return undefined;\n }\n\n return cleanUpFastlaneStyles(mergeFastlaneStyles(styleSettings, uiStyles));\n}\n\nfunction mergeFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: BraintreeFastlaneStylesOption,\n): BraintreeFastlaneStylesOption {\n return {\n root: {\n backgroundColorPrimary:\n styleSettings?.fastlaneRootSettingsBackgroundColor ||\n uiStyles?.root?.backgroundColorPrimary,\n errorColor: styleSettings?.fastlaneRootSettingsErrorColor || uiStyles?.root?.errorColor,\n fontFamily: styleSettings?.fastlaneRootSettingsFontFamily || uiStyles?.root?.fontFamily,\n fontSizeBase:\n styleSettings?.fastlaneRootSettingsFontSize || uiStyles?.root?.fontSizeBase,\n padding: styleSettings?.fastlaneRootSettingsPadding || uiStyles?.root?.padding,\n primaryColor:\n styleSettings?.fastlaneRootSettingsPrimaryColor || uiStyles?.root?.primaryColor,\n },\n input: {\n borderRadius:\n styleSettings?.fastlaneInputSettingsBorderRadius || uiStyles?.input?.borderRadius,\n borderColor:\n styleSettings?.fastlaneInputSettingsBorderColor || uiStyles?.input?.borderColor,\n focusBorderColor:\n styleSettings?.fastlaneInputSettingsFocusBorderBase ||\n uiStyles?.input?.focusBorderColor,\n backgroundColor:\n styleSettings?.fastlaneInputSettingsBackgroundColor ||\n uiStyles?.input?.backgroundColor,\n borderWidth:\n styleSettings?.fastlaneInputSettingsBorderWidth || uiStyles?.input?.borderWidth,\n textColorBase:\n styleSettings?.fastlaneInputSettingsTextColorBase || uiStyles?.input?.textColorBase,\n },\n toggle: {\n colorPrimary:\n styleSettings?.fastlaneToggleSettingsColorPrimary || uiStyles?.toggle?.colorPrimary,\n colorSecondary:\n styleSettings?.fastlaneToggleSettingsColorSecondary ||\n uiStyles?.toggle?.colorSecondary,\n },\n text: {\n body: {\n color: styleSettings?.fastlaneTextBodySettingsColor || uiStyles?.text?.body?.color,\n fontSize:\n styleSettings?.fastlaneTextBodySettingsFontSize ||\n uiStyles?.text?.body?.fontSize,\n },\n caption: {\n color:\n styleSettings?.fastlaneTextCaptionSettingsColor ||\n uiStyles?.text?.caption?.color,\n fontSize:\n styleSettings?.fastlaneTextCaptionSettingsFontSize ||\n uiStyles?.text?.caption?.fontSize,\n },\n },\n branding: styleSettings?.fastlaneBrandingSettings || uiStyles?.branding,\n };\n}\n\nfunction cleanUpFastlaneStyles(styles: BraintreeFastlaneStylesOption) {\n const fastlaneStyles: BraintreeFastlaneStylesOption = {};\n\n const root = omitBy(styles.root, isInvalidStyleOption);\n const input = omitBy(styles.input, isInvalidStyleOption);\n const toggle = omitBy(styles.toggle, isInvalidStyleOption);\n const textBody = omitBy(styles.text?.body, isInvalidStyleOption);\n const textCaption = omitBy(styles.text?.caption, isInvalidStyleOption);\n const branding = styles.branding;\n\n if (Object.keys(root).length) {\n fastlaneStyles.root = root;\n }\n\n if (Object.keys(input).length) {\n fastlaneStyles.input = input;\n }\n\n if (Object.keys(toggle).length) {\n fastlaneStyles.toggle = toggle;\n }\n\n if (Object.keys(textBody).length) {\n fastlaneStyles.text = {};\n fastlaneStyles.text.body = textBody;\n }\n\n if (Object.keys(textCaption).length) {\n fastlaneStyles.text = {\n ...fastlaneStyles.text,\n };\n fastlaneStyles.text.caption = textCaption;\n }\n\n if (branding) {\n fastlaneStyles.branding = branding;\n }\n\n return fastlaneStyles;\n}\n","import {\n BraintreeInitializationData,\n getFastlaneStyles,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeFastlaneCustomerInitializeOptions } from './braintree-fastlane-customer-initialize-options';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nexport default class BraintreeFastlaneCustomerStrategy implements CustomerStrategy {\n private isAcceleratedCheckoutEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n ) {}\n\n async initialize({\n methodId,\n braintreefastlane,\n }: CustomerInitializeOptions & WithBraintreeFastlaneCustomerInitializeOptions): Promise {\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = await this.getValidPaymentMethodOrThrow(methodId);\n\n const { isAcceleratedCheckoutEnabled, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n const paypalFastlaneStylesSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\n\n this.isAcceleratedCheckoutEnabled = !!isAcceleratedCheckoutEnabled;\n\n try {\n if (this.isAcceleratedCheckoutEnabled) {\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStylesSettings,\n braintreefastlane?.styles,\n );\n\n await this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(\n paymentMethod.id,\n fastlaneStyles,\n );\n }\n } catch (_) {\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n\n return Promise.resolve();\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const { checkoutPaymentMethodExecuted, continueWithCheckoutCallback } = options || {};\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomerOrThrow();\n\n if (this.isAcceleratedCheckoutEnabled && customer.isGuest) {\n const shouldRunAuthenticationFlow = await this.shouldRunAuthenticationFlow();\n\n if (\n checkoutPaymentMethodExecuted &&\n typeof checkoutPaymentMethodExecuted === 'function'\n ) {\n checkoutPaymentMethodExecuted();\n }\n\n if (shouldRunAuthenticationFlow) {\n await this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow(\n undefined,\n true,\n );\n }\n }\n\n continueWithCheckoutCallback();\n }\n\n // TODO: remove this method after A/B testing finished\n private async shouldRunAuthenticationFlow(): Promise {\n const primaryMethodId = 'braintreeacceleratedcheckout';\n\n try {\n // Info: we should load payment method each time to detect if the user\n // should be in a test or in a control group\n await this.paymentIntegrationService.loadPaymentMethod(primaryMethodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(primaryMethodId);\n\n // Info: shouldRunAcceleratedCheckout is responsible for the flow of A/B testing purposes\n // when shouldRunAcceleratedCheckout is true, the lookup PayPal Connect method should be called,\n // otherwise AcceleratedCheckout should not be available for the customer\n return paymentMethod.initializationData?.shouldRunAcceleratedCheckout || false;\n } catch (_) {\n return false;\n }\n }\n\n private async getValidPaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n let validPaymentMethodId = methodId;\n\n try {\n await this.paymentIntegrationService.loadPaymentMethod(validPaymentMethodId);\n } catch {\n validPaymentMethodId =\n methodId === 'braintree' ? 'braintreeacceleratedcheckout' : 'braintree';\n await this.paymentIntegrationService.loadPaymentMethod(validPaymentMethodId);\n }\n\n return this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(validPaymentMethodId);\n }\n}\n","type PaymentInstrument = CardInstrument | AccountInstrument;\n\nexport default PaymentInstrument;\n\ninterface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport enum UntrustedShippingCardVerificationType {\n CVV = 'cvv',\n PAN = 'pan',\n}\n\nexport interface CardInstrument extends BaseInstrument {\n brand: string;\n expiryMonth: string;\n expiryYear: string;\n iin: string;\n last4: string;\n type: 'card';\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType;\n}\n\ninterface BaseAccountInstrument extends BaseInstrument {\n method: string;\n type: 'account' | 'bank';\n}\n\nexport interface PayPalInstrument extends BaseAccountInstrument {\n externalId: string;\n method: 'paypal';\n}\n\nexport interface AchInstrument extends BaseAccountInstrument {\n issuer: string;\n accountNumber: string;\n type: 'bank';\n method: 'ach' | 'ecp';\n}\n\nexport interface BankInstrument extends BaseAccountInstrument {\n accountNumber: string;\n issuer: string;\n iban: string;\n method: string;\n type: 'bank';\n}\n\nexport type AccountInstrument = PayPalInstrument | BankInstrument | AchInstrument;\n\nexport interface VaultAccessToken {\n vaultAccessToken: string;\n vaultAccessExpiry: number;\n}\n\nexport interface SessionContext {\n customerId: number;\n storeId: string;\n currencyCode?: string;\n}\n\nexport interface InstrumentRequestContext extends SessionContext {\n authToken: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlane,\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeInitializationData,\n BraintreeIntegrationService,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CardInstrument,\n CustomerAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n UntrustedShippingCardVerificationType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nexport default class BraintreeFastlaneUtils {\n private braintreeFastlane?: BraintreeFastlane;\n private methodId?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private browserStorage: BrowserStorage,\n ) {}\n\n async getDeviceSessionId(): Promise {\n const cart = this.paymentIntegrationService.getState().getCart();\n\n return this.braintreeIntegrationService.getSessionId(cart?.id);\n }\n\n /**\n *\n * Initialization method\n *\n */\n async initializeBraintreeFastlaneOrThrow(\n methodId: string,\n styles?: BraintreeFastlaneStylesOption,\n ) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCart();\n const { clientToken, config } =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.methodId = methodId;\n\n this.braintreeIntegrationService.initialize(clientToken);\n\n this.braintreeFastlane = await this.braintreeIntegrationService.getBraintreeFastlane(\n cart?.id,\n config.testMode,\n styles,\n );\n }\n\n getBraintreeFastlaneOrThrow(): BraintreeFastlane {\n if (!this.braintreeFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeFastlane;\n }\n\n getBraintreeFastlaneComponentOrThrow(): BraintreeFastlane['FastlaneCardComponent'] {\n const braintreeFastlane = this.getBraintreeFastlaneOrThrow();\n\n return braintreeFastlane.FastlaneCardComponent;\n }\n\n /**\n *\n * Authentication methods\n *\n * */\n // Remove this rule disabling after method refactor\n // eslint-disable-next-line complexity\n async runPayPalAuthenticationFlowOrThrow(\n email?: string,\n shouldSetShippingOption?: boolean,\n ): Promise {\n try {\n const methodId = this.getMethodIdOrThrow();\n const braintreeFastlane = this.getBraintreeFastlaneOrThrow();\n const { lookupCustomerByEmail, triggerAuthenticationFlow } = braintreeFastlane.identity;\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const { isFastlaneShippingOptionAutoSelectEnabled } =\n state.getPaymentMethodOrThrow(methodId)\n .initializationData || {};\n\n const customerEmail = email || customer?.email || billingAddress?.email || '';\n\n const { customerContextId } = await lookupCustomerByEmail(customerEmail);\n\n if (!customerContextId) {\n // Info: we should clean up previous experience with default data and related authenticationState\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState: BraintreeFastlaneAuthenticationState.UNRECOGNIZED,\n addresses: [],\n instruments: [],\n });\n\n this.browserStorage.setItem('sessionId', cart.id);\n\n return;\n }\n\n const { authenticationState, profileData } = await triggerAuthenticationFlow(\n customerContextId,\n );\n\n const phoneNumber = profileData?.shippingAddress?.phoneNumber || '';\n\n if (authenticationState === BraintreeFastlaneAuthenticationState.CANCELED) {\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses: [],\n instruments: [],\n });\n\n this.browserStorage.removeItem('sessionId');\n\n return;\n }\n\n const shippingAddresses =\n this.mapPayPalToBcAddress([profileData.shippingAddress], [phoneNumber]) || [];\n const paypalBillingAddress = this.getPayPalBillingAddresses(profileData);\n const billingAddresses = paypalBillingAddress\n ? this.mapPayPalToBcAddress([paypalBillingAddress], [phoneNumber])\n : [];\n const instruments = profileData.card\n ? this.mapPayPalToBcInstrument(methodId, [profileData.card])\n : [];\n const addresses = this.mergeShippingAndBillingAddresses(\n shippingAddresses,\n billingAddresses,\n );\n\n this.browserStorage.setItem('sessionId', cart.id);\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n if (billingAddresses.length > 0 && cart.lineItems.physicalItems.length > 0) {\n await this.paymentIntegrationService.updateBillingAddress(billingAddresses[0]);\n }\n\n // Prefill billing form if only digital items in cart with billing data and firstName and lastName\n // from shippingAddresses because there are empty in billing\n if (\n billingAddresses.length > 0 &&\n cart.lineItems.digitalItems.length > 0 &&\n cart.lineItems.physicalItems.length === 0\n ) {\n const { firstName, lastName } = addresses[0];\n const digitalItemBilling = {\n ...billingAddresses[0],\n firstName,\n lastName,\n };\n\n await this.paymentIntegrationService.updateBillingAddress(digitalItemBilling);\n }\n\n if (shippingAddresses.length > 0 && cart.lineItems.physicalItems.length > 0) {\n await this.paymentIntegrationService.updateShippingAddress(shippingAddresses[0]);\n\n if (shouldSetShippingOption && isFastlaneShippingOptionAutoSelectEnabled) {\n await this.setShippingOption();\n }\n }\n } catch (error) {\n // TODO: we should figure out what to do here\n // TODO: because we should not to stop the flow if the error occurs on paypal side\n }\n }\n\n /**\n *\n * PayPal to BC data mappers\n *\n * */\n mapPayPalToBcInstrument(\n methodId: string,\n instruments?: BraintreeFastlaneVaultedInstrument[],\n ): CardInstrument[] | undefined {\n if (!instruments) {\n return;\n }\n\n return instruments.map((instrument) => {\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n type: 'card',\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.PAN,\n };\n });\n }\n\n private mapPayPalToBcAddress(\n addresses?: BraintreeFastlaneAddress[],\n phones?: string[],\n ): CustomerAddress[] {\n if (!addresses) {\n return [];\n }\n\n const countries = this.paymentIntegrationService.getState().getCountries() || [];\n\n const getCountryNameByCountryCode = (countryCode: string) => {\n const matchedCountry = countries.find((country) => country.code === countryCode);\n\n return matchedCountry?.name || '';\n };\n\n return addresses.map((address) => ({\n id: Date.now(),\n type: 'paypal-address',\n firstName: address.firstName || '',\n lastName: address.lastName || '',\n company: address.company || '',\n address1: address.streetAddress,\n address2: address.extendedAddress || '',\n city: address.locality,\n stateOrProvince: address.region,\n stateOrProvinceCode: address.region,\n country: getCountryNameByCountryCode(address.countryCodeAlpha2),\n countryCode: address.countryCodeAlpha2,\n postalCode: address.postalCode,\n phone: (phones && phones[0]) || '',\n customFields: [],\n }));\n }\n\n /**\n *\n * Get PayPal billing addresses from stored braintree instruments info\n *\n * */\n private getPayPalBillingAddresses(\n profileData?: BraintreeFastlaneProfileData,\n ): BraintreeFastlaneAddress | undefined {\n const { card, name } = profileData || {};\n\n if (!card) {\n return;\n }\n\n const { firstName, lastName } = card.paymentSource.card.billingAddress;\n const { firstName: given_name, lastName: surname } = name || {};\n const { shippingAddress } = profileData || {};\n const address = {\n ...card.paymentSource.card.billingAddress,\n firstName: firstName || given_name,\n lastName: lastName || surname,\n };\n\n const isAddressExist =\n shippingAddress &&\n isEqual(this.normalizeAddress(address), this.normalizeAddress(shippingAddress));\n\n return isAddressExist ? shippingAddress : address;\n }\n\n private normalizeAddress(address: CustomerAddress | BraintreeFastlaneAddress) {\n return omit(address, ['id']);\n }\n\n private mergeShippingAndBillingAddresses(\n shippingAddresses: CustomerAddress[],\n billingAddresses: CustomerAddress[],\n ): CustomerAddress[] {\n const filteredBillingAddresses = billingAddresses.filter(\n (billingAddress: CustomerAddress) =>\n !shippingAddresses.some((shippingAddress: CustomerAddress) => {\n return isEqual(\n this.normalizeAddress(shippingAddress),\n this.normalizeAddress(billingAddress),\n );\n }),\n );\n\n return [...shippingAddresses, ...filteredBillingAddresses];\n }\n\n /**\n *\n * Other\n *\n * */\n private getMethodIdOrThrow(): string {\n if (!this.methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n return this.methodId;\n }\n\n private async setShippingOption(): Promise {\n const state = this.paymentIntegrationService.getState();\n const consignments = state.getConsignments() || [];\n const availableShippingOptions = consignments[0]?.availableShippingOptions || [];\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n if (recommendedShippingOption || availableShippingOptions.length) {\n const selectedOption = recommendedShippingOption || availableShippingOptions[0];\n\n await this.paymentIntegrationService.selectShippingOption(selectedOption.id);\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport BraintreeFastlaneCustomerStrategy from './braintree-fastlane-customer-strategy';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nconst createBraintreeFastlaneCustomerStrategy: CustomerStrategyFactory<\n BraintreeFastlaneCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n const browserStorage = new BrowserStorage('paypalFastlane');\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n browserStorage,\n );\n\n return new BraintreeFastlaneCustomerStrategy(paymentIntegrationService, braintreeFastlaneUtils);\n};\n\n// Info: braintree method id was added only for A/B testing purposes.\n// The main reason why we can't go in other way, because braintreeacceleratedcheckout\n// may be turned on only when BE knows customer's email address (to understand should we show the feature for the user or not).\n// So { id: 'braintree' }, should be removed after A/B testing\nexport default toResolvableModule(createBraintreeFastlaneCustomerStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n { id: 'braintree' },\n]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeDataCollector,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithBraintreeVisaCheckoutCustomerInitializeOptions } from './braintree-visa-customer-initialize-options';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private buttonClassName = 'visa-checkout-wrapper';\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreeVisaCheckoutCustomerInitializeOptions,\n ): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const checkout = state.getCheckoutOrThrow();\n\n const { clientToken, config } = state.getPaymentMethodOrThrow(methodId);\n\n const storeConfig = state.getStoreConfigOrThrow();\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const visaCheckoutInstance = await this.braintreeSdk.getVisaCheckoutSdk(config.testMode);\n\n const { container, onError } = visaCheckoutOptions;\n\n this.onError = onError || noop;\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n paymentRequest: {\n currencyCode: storeConfig.currency.code,\n subtotal: String(checkout.subtotal),\n },\n settings: {\n locale: storeConfig.storeProfile.storeLanguage,\n shipping: {\n collectShipping: true,\n },\n },\n });\n\n const signInButton = this.createSignInButton(container, this.buttonClassName);\n\n await visaCheckoutInstance.init(initOptions);\n\n visaCheckoutInstance.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this.tokenizePayment(braintreeVisaCheckout, paymentSuccessPayload)\n .then(() => this.paymentIntegrationService.loadCheckout())\n .catch((error) => this.handleError(error)),\n );\n\n visaCheckoutInstance.on('payment.error', (_, error) => this.handleError(error));\n\n signInButton.style.visibility = 'visible';\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private async tokenizePayment(\n braintreeVisaCheckout: BraintreeVisaCheckout,\n payment: VisaCheckoutPaymentSuccessPayload,\n ) {\n return Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this.braintreeSdk.getDataCollectorOrThrow(),\n ]).then(([payload, deviceData]) => {\n const state = this.paymentIntegrationService.getState();\n\n const shipping = state.getShippingAddress();\n const billing = state.getBillingAddress();\n\n const {\n shippingAddress = this.mapToVisaCheckoutAddress(shipping),\n billingAddress = this.mapToVisaCheckoutAddress(billing),\n } = payload;\n\n return this.postForm(\n {\n ...payload,\n shippingAddress,\n billingAddress,\n },\n deviceData,\n );\n });\n }\n\n private postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: JSON.stringify({\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n }),\n billing_address: JSON.stringify(this.getAddress(userEmail, billingAddress)),\n shipping_address: JSON.stringify(this.getAddress(userEmail, shippingAddress)),\n });\n }\n\n private mapToVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Unable to proceed because the provided container ID is not valid.');\n }\n\n return this.insertVisaCheckoutButton(container, buttonClass);\n }\n\n private insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.style.width = 'max-content';\n\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutCustomerStrategy from './braintree-visa-checkout-customer-strategy';\n\nconst createBraintreeVisaCheckoutCustomerStrategy: CustomerStrategyFactory<\n BraintreeVisaCheckoutCustomerStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), hostWindow));\n\n return new BraintreeVisaCheckoutCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutCustomerStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","/**\n * Decorates a class or a method by binding all its prototype methods or itself\n * to the calling instance respectively.\n */\nfunction bindDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor;\nfunction bindDecorator>(target: T): T;\n\nfunction bindDecorator(target: any, key?: any, descriptor?: any): any {\n if (!key || !descriptor) {\n return bindClassDecorator(target);\n }\n\n return bindMethodDecorator(target, key, descriptor);\n}\n\nexport default bindDecorator;\n\n/**\n * Decorates a class by binding all its prototype methods to the calling\n * instance.\n */\nexport function bindClassDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n bindMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\n/**\n * Decorates a method by binding it to the calling instance.\n */\nexport function bindMethodDecorator(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let method: T = descriptor.value;\n\n return {\n get() {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const boundMethod = method.bind(this) as T;\n\n Object.defineProperty(this, key, {\n ...descriptor,\n value: boundMethod,\n });\n\n return boundMethod;\n },\n set(value) {\n method = value;\n },\n };\n}\n\nexport type Constructor = new (...args: any[]) => T;\nexport type Method = (...args: any[]) => any;\n","import { InvalidArgumentError } from '../errors';\n\nimport { CurrencyConfig } from './currency';\n\nexport default class CurrencyFormatter {\n private _decimalPlaces: number;\n private _symbolLocation: string;\n private _symbol: string;\n private _thousandsSeparator: string;\n private _decimalSeparator: string;\n\n constructor(currencySettings: CurrencyConfig) {\n if (!currencySettings) {\n throw new Error('Currency settings missing');\n }\n\n const { decimalPlaces, symbolLocation, symbol, thousandsSeparator, decimalSeparator } =\n currencySettings;\n\n if (\n typeof symbolLocation !== 'string' ||\n typeof symbol !== 'string' ||\n typeof thousandsSeparator !== 'string' ||\n typeof decimalSeparator !== 'string' ||\n typeof decimalPlaces !== 'string'\n ) {\n throw new InvalidArgumentError('Invalid currency settings provided');\n }\n\n this._decimalPlaces = parseInt(decimalPlaces, 10);\n this._symbolLocation = symbolLocation;\n this._symbol = symbol;\n this._thousandsSeparator = thousandsSeparator;\n this._decimalSeparator = decimalSeparator;\n }\n\n format(amount?: number): string {\n if (typeof amount !== 'number') {\n throw new InvalidArgumentError('Invalid amount provided');\n }\n\n const formattedNumber = this._formatNumber(amount);\n\n const formattedCurrency = this._formatCurrency(formattedNumber);\n\n return amount < 0 ? `-${formattedCurrency}` : formattedCurrency;\n }\n\n private _formatNumber(amount: number): string {\n const positiveAmount = Math.abs(amount);\n const [integerAmount, decimalAmount = ''] = this._toFixed(\n positiveAmount,\n this._decimalPlaces,\n ).split('.');\n const parsedIntegerAmount = integerAmount.replace(\n /\\B(?=(\\d{3})+(?!\\d))/g,\n this._thousandsSeparator,\n );\n\n if (this._decimalPlaces < 1) {\n return parsedIntegerAmount;\n }\n\n return [parsedIntegerAmount, decimalAmount].join(this._decimalSeparator);\n }\n\n private _formatCurrency(formattedNumber: string): string {\n return this._symbolLocation.toLowerCase() === 'left'\n ? `${this._symbol}${formattedNumber}`\n : `${formattedNumber}${this._symbol}`;\n }\n\n private _toFixed(value: number, precision: number): string {\n return (+`${Math.round(+`${value}e${precision}`)}e${-precision}`).toFixed(precision);\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { StoreConfig } from '../config';\n\nimport CurrencyFormatter from './currency-formatter';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { Cart } from '../cart';\nimport { StoreConfig } from '../config';\n\nconst itemsRequireShipping = (cart?: Cart, config?: StoreConfig) => {\n if (!cart) {\n return false;\n }\n\n if (cart.lineItems.physicalItems.some((lineItem) => lineItem.isShippingRequired)) {\n return true;\n }\n\n if (config && cart.lineItems.customItems) {\n return cart.lineItems.customItems.length > 0;\n }\n\n return false;\n};\n\nexport default itemsRequireShipping;\n","import {\n BrowserInfo,\n BuyNowCartRequestBody,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { FundingType } from './google-pay-paypal-commerce/types';\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\nexport interface GooglePayGatewayBaseRequest {\n apiVersion: 2;\n apiVersionMinor: 0;\n}\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\ntype GooglePayGatewayBaseResponse = GooglePayGatewayBaseRequest;\n\ninterface GooglePayPaymentMethod {\n type: string;\n parameters: T;\n}\n\ntype GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS';\n\nexport enum GooglePayCardNetwork {\n AMEX = 'AMEX',\n DISCOVER = 'DISCOVER',\n INTERAC = 'INTERAC',\n JCB = 'JCB',\n MC = 'MASTERCARD',\n VISA = 'VISA',\n}\n\nexport interface GooglePayCardParameters {\n allowedAuthMethods: GooglePayAuthMethod[];\n allowedCardNetworks: GooglePayCardNetwork[];\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: 'MIN' | 'FULL';\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface GooglePayBaseCardPaymentMethod\n extends GooglePayPaymentMethod {\n type: 'CARD';\n parameters: GooglePayCardParameters;\n}\n\nexport interface GooglePayIsReadyToPayRequest extends GooglePayGatewayBaseRequest {\n allowedPaymentMethods: [GooglePayBaseCardPaymentMethod];\n}\n\ninterface GooglePayGatewayBaseParameters {\n gateway: string;\n}\n\nexport interface GooglePayRegularGatewayParameters extends GooglePayGatewayBaseParameters {\n gatewayMerchantId: string;\n}\n\nexport interface GooglePayStripeGatewayParameters extends GooglePayGatewayBaseParameters {\n 'stripe:version'?: string;\n 'stripe:publishableKey'?: string;\n}\n\nexport interface GooglePayBraintreeGatewayParameters extends GooglePayGatewayBaseParameters {\n 'braintree:apiVersion'?: string;\n 'braintree:authorizationFingerprint'?: string;\n 'braintree:merchantId'?: string;\n 'braintree:sdkVersion'?: string;\n}\n\nexport interface GooglePayPayPalCommerceGatewayParameters extends GooglePayGatewayBaseParameters {\n gatewayMerchantId?: string;\n}\n\nexport type GooglePayGatewayParameters =\n | GooglePayRegularGatewayParameters\n | GooglePayStripeGatewayParameters\n | GooglePayBraintreeGatewayParameters;\n\nexport interface GooglePayCardPaymentMethod extends GooglePayBaseCardPaymentMethod {\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY';\n parameters: GooglePayGatewayParameters;\n };\n}\n\nexport interface GooglePayTransactionInfo {\n /** [!] Required for EEA countries */\n countryCode?: string;\n currencyCode: string;\n totalPriceStatus: TotalPriceStatusType;\n totalPrice: string;\n}\n\nexport interface GooglePayMerchantInfo {\n merchantName: string;\n merchantId: string;\n authJwt: string;\n}\n\nexport enum CallbackIntentsType {\n OFFER = 'OFFER',\n PAYMENT_AUTHORIZATION = 'PAYMENT_AUTHORIZATION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n}\n\nexport interface GooglePayPaymentDataRequest extends GooglePayGatewayBaseRequest {\n allowedPaymentMethods: [GooglePayCardPaymentMethod];\n transactionInfo: GooglePayTransactionInfo;\n merchantInfo: GooglePayMerchantInfo;\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n shippingOptionRequired?: boolean;\n callbackIntents?: CallbackIntentsType[];\n}\n\nexport interface NewTransactionInfo {\n newTransactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport interface ShippingOptionParameters {\n defaultSelectedOptionId?: string;\n shippingOptions?: GoogleShippingOption[];\n}\n\nexport interface NewShippingOptionParameters {\n newShippingOptionParameters?: ShippingOptionParameters;\n}\n\nexport interface GoogleShippingOption {\n id: string;\n label?: string;\n}\n\nexport enum CallbackTriggerType {\n INITIALIZE = 'INITIALIZE',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n OFFER = 'OFFER',\n}\n\nexport interface IntermediatePaymentData {\n callbackTrigger: CallbackTriggerType;\n shippingAddress: GooglePayFullBillingAddress;\n shippingOptionData: GoogleShippingOption;\n}\n\nexport interface GooglePayPaymentOptions {\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): Promise<(NewTransactionInfo & NewShippingOptionParameters) | void>;\n };\n}\n\nexport type GooglePayRequiredPaymentData = Pick<\n GooglePayPaymentDataRequest,\n | 'emailRequired'\n | 'shippingAddressRequired'\n | 'shippingAddressParameters'\n | 'shippingOptionRequired'\n>;\n\ninterface GooglePayMinBillingAddress {\n name: string;\n postalCode: string;\n countryCode: string;\n phoneNumber?: string;\n}\n\nexport interface GooglePayFullBillingAddress extends GooglePayMinBillingAddress {\n address1: string;\n address2: string;\n address3: string;\n locality: string;\n administrativeArea: string;\n sortingCode: string;\n}\n\ninterface GooglePayCardInfo {\n cardNetwork: GooglePayCardNetwork;\n cardDetails: string;\n billingAddress?: GooglePayFullBillingAddress;\n}\n\ninterface GooglePayPaymentMethodData {\n description: string;\n tokenizationData: {\n type: 'PAYMENT_GATEWAY';\n token: string;\n };\n type: string;\n info: T;\n}\n\ninterface GooglePayCardData extends GooglePayPaymentMethodData {\n type: 'CARD';\n}\n\ninterface GooglePayPaymentDataResponse extends GooglePayGatewayBaseResponse {\n paymentMethodData: GooglePayPaymentMethodData;\n shippingAddress?: GooglePayFullBillingAddress;\n email?: string;\n}\n\nexport interface GooglePayCardDataResponse extends GooglePayPaymentDataResponse {\n paymentMethodData: GooglePayCardData;\n}\n\ninterface GooglePayIsReadyToPayResponse {\n result: boolean;\n}\n\nexport interface GooglePayButtonOptions {\n onClick: (event: MouseEvent) => void;\n allowedPaymentMethods: [GooglePayBaseCardPaymentMethod];\n buttonColor?: GooglePayButtonColor;\n buttonType?: GooglePayButtonType;\n}\n\nexport interface GooglePaymentsClient {\n isReadyToPay(request: GooglePayIsReadyToPayRequest): Promise;\n createButton(options: GooglePayButtonOptions): HTMLElement;\n loadPaymentData(request: GooglePayPaymentDataRequest): Promise;\n prefetchPaymentData(request: GooglePayPaymentDataRequest): void;\n}\n\ntype GooglePayEnvironment = 'TEST' | 'PRODUCTION';\n\nexport type GooglePaymentsClientConstructor = new (paymentOptions: {\n environment: GooglePayEnvironment;\n}) => GooglePaymentsClient;\n\nexport interface GooglePayHostWindow extends Window {\n google?: {\n payments: {\n api: {\n PaymentsClient: GooglePaymentsClientConstructor;\n };\n };\n };\n}\n\ninterface GooglePayBaseInitializationData {\n card_information?: { type: string; number: string; bin?: string; isNetworkTokenized?: boolean };\n gateway: string;\n gatewayMerchantId?: string;\n googleMerchantId: string;\n googleMerchantName: string;\n isThreeDSecureEnabled: boolean;\n nonce?: string;\n platformToken: string;\n storeCountry?: string;\n}\n\nexport interface GooglePayPayPalCommerceInitializationData extends GooglePayBaseInitializationData {\n merchantId?: string;\n clientId?: string;\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n orderId?: string;\n shouldRenderFields?: boolean;\n paymentButtonStyles?: Record;\n}\n\nexport interface GooglePayAuthorizeNetInitializationData extends GooglePayBaseInitializationData {\n paymentGatewayId: string;\n}\n\nexport interface GooglePayStripeInitializationData extends GooglePayBaseInitializationData {\n stripeConnectedAccount: string;\n stripePublishableKey: string;\n stripeVersion: string;\n}\n\nexport interface GooglePayCheckoutComInitializationData extends GooglePayBaseInitializationData {\n checkoutcomkey: string;\n}\n\nexport interface GooglePayAdyenV2InitializationData extends GooglePayBaseInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n prefillCardHolderName?: boolean;\n paymentMethodsResponse: object;\n}\n\nexport interface GooglePayAdyenV3InitializationData extends GooglePayBaseInitializationData {\n clientKey: string;\n environment?: string;\n prefillCardHolderName?: boolean;\n paymentMethodsResponse: object;\n}\n\nexport type GooglePayInitializationData =\n | GooglePayBaseInitializationData\n | GooglePayAdyenV2InitializationData\n | GooglePayAdyenV3InitializationData\n | GooglePayAuthorizeNetInitializationData\n | GooglePayStripeInitializationData\n | GooglePayCheckoutComInitializationData\n | GooglePayPayPalCommerceInitializationData;\n\nexport interface GooglePaySetExternalCheckoutData {\n nonce: string;\n card_information: { type: string; number: string; bin?: string; isNetworkTokenized?: boolean };\n cart_id?: string;\n}\n\nexport interface GooglePayAdditionalActionProcessable {\n processAdditionalAction(error: unknown, methodId?: string): Promise;\n}\n\nexport interface GooglePayErrorObject {\n errorCode?: number;\n statusCode: 'CANCELED' | 'DEVELOPER_ERROR';\n statusMessage?: string;\n}\n\nexport interface GooglePayTokenObject {\n protocolVersion: string;\n signature: string;\n signedMessage: string;\n}\n\nexport interface GooglePayStripeTokenObject {\n id: string;\n}\n\nexport interface GooglePayBraintreeTokenObject {\n androidPayCards: [\n {\n nonce: string;\n details: {\n bin: string;\n isNetworkTokenized?: boolean;\n };\n },\n ];\n}\n\nexport interface GooglePayCheckoutComTokenObject {\n token: string;\n}\n\nexport interface GooglePayThreeDSecureResult {\n three_ds_result: {\n acs_url: string;\n code: string;\n };\n}\n\nexport interface GooglePayBuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody;\n}\n\nexport interface ExtraPaymentData {\n deviceSessionId?: string;\n browser_info?: BrowserInfo;\n}\n\nexport type GooglePayButtonColor = 'default' | 'black' | 'white';\nexport type GooglePayButtonType =\n | 'book'\n | 'buy'\n | 'checkout'\n | 'donate'\n | 'order'\n | 'pay'\n | 'plain'\n | 'subscribe'\n | 'long'\n | 'short';\n\nexport interface TdOnlineMartThreeDSErrorBody {\n errors?: Array<{ code: string }>;\n three_ds_result?: {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n };\n}\n\nexport type TdOnlineMartAdditionalAction = RequestError;\n","import { GooglePayCardNetwork } from '../types';\n\nexport default function isGooglePayCardNetworkKey(\n card: string,\n): card is keyof typeof GooglePayCardNetwork {\n return card in GooglePayCardNetwork;\n}\n","import { round } from 'lodash';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n createCurrencyService,\n CurrencyService,\n guard,\n InvalidArgumentError,\n itemsRequireShipping,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isGooglePayCardNetworkKey from '../guards/is-google-pay-card-network-key';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n ExtraPaymentData,\n GooglePayCardDataResponse,\n GooglePayCardNetwork,\n GooglePayCardParameters,\n GooglePayFullBillingAddress,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePayMerchantInfo,\n GooglePayRequiredPaymentData,\n GooglePaySetExternalCheckoutData,\n GooglePayTransactionInfo,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from '../types';\n\nexport default class GooglePayGateway {\n private _getPaymentMethodFn?: () => PaymentMethod;\n private _isBuyNowFlow = false;\n private _currencyCode?: string;\n private _currencyService?: CurrencyService;\n\n constructor(\n private _gatewayIdentifier: string,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n mapToShippingAddressRequestBody({\n shippingAddress,\n }: GooglePayCardDataResponse): AddressRequestBody | undefined {\n if (!shippingAddress) {\n return;\n }\n\n const { company = '', phone = '' } =\n this._paymentIntegrationService.getState().getShippingAddress() || {};\n\n return this._mapToAddressRequestBody(shippingAddress, company, phone);\n }\n\n mapToBillingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): BillingAddressRequestBody | undefined {\n const { billingAddress } = response.paymentMethodData.info;\n\n if (!billingAddress) {\n return;\n }\n\n const {\n company = '',\n phone = '',\n email,\n } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n return {\n ...this._mapToAddressRequestBody(billingAddress, company, phone),\n email: email || response.email,\n };\n }\n\n mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const {\n paymentMethodData: {\n tokenizationData: { token: nonce },\n info: { cardNetwork: type, cardDetails: number },\n },\n } = response;\n\n return Promise.resolve({\n nonce,\n card_information: { type, number },\n ...(this._isBuyNowFlow && {\n cart_id: this._paymentIntegrationService.getState().getCart()?.id,\n }),\n });\n }\n\n async getRequiredData(): Promise {\n const data: GooglePayRequiredPaymentData = { emailRequired: true };\n\n if (!this._isShippingAddressRequired()) {\n return data;\n }\n\n const state = await this._paymentIntegrationService.loadShippingCountries();\n const allowedCountryCodes = state.getShippingCountries()?.map((country) => country.code);\n\n return {\n ...data,\n shippingAddressRequired: true,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n ...(allowedCountryCodes && { allowedCountryCodes }),\n },\n shippingOptionRequired: true,\n };\n }\n\n getCallbackIntents(): CallbackIntentsType[] {\n if (this._isShippingAddressRequired()) {\n return [\n CallbackIntentsType.OFFER,\n CallbackIntentsType.SHIPPING_ADDRESS,\n CallbackIntentsType.SHIPPING_OPTION,\n ];\n }\n\n return [CallbackIntentsType.OFFER];\n }\n\n getCallbackTriggers(): { [key: string]: CallbackTriggerType[] } {\n const availableTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n CallbackTriggerType.SHIPPING_OPTION,\n ];\n const initializationTrigger = [CallbackTriggerType.INITIALIZE];\n const addressChangeTriggers = [\n CallbackTriggerType.INITIALIZE,\n CallbackTriggerType.SHIPPING_ADDRESS,\n ];\n const shippingOptionsChangeTriggers = [CallbackTriggerType.SHIPPING_OPTION];\n\n return {\n availableTriggers,\n initializationTrigger,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n };\n }\n\n getNonce(methodId: string) {\n const nonce = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId)\n .initializationData?.nonce;\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return Promise.resolve(nonce);\n }\n\n extraPaymentData(): Promise {\n return Promise.resolve(undefined);\n }\n\n getMerchantInfo(): GooglePayMerchantInfo {\n const {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n } = this.getGooglePayInitializationData();\n\n return { merchantName, merchantId, authJwt };\n }\n\n getTransactionInfo(): GooglePayTransactionInfo {\n let currencyCode: string;\n\n if (this._isBuyNowFlow) {\n currencyCode = this._getCurrencyCodeOrThrow();\n } else {\n const { getCartOrThrow } = this._paymentIntegrationService.getState();\n\n currencyCode = getCartOrThrow().currency.code;\n }\n\n const countryCode = this.getGooglePayInitializationData().storeCountry;\n\n return {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n totalPrice: '0',\n };\n }\n\n getPaymentGatewayParameters():\n | Promise\n | GooglePayGatewayParameters {\n const gatewayMerchantId = this.getGooglePayInitializationData().gatewayMerchantId;\n\n if (!gatewayMerchantId) {\n throw new InvalidArgumentError('Unable to proceed, gatewayMerchantId is missing.');\n }\n\n return {\n gateway: this._gatewayIdentifier,\n gatewayMerchantId,\n };\n }\n\n getCardParameters(): GooglePayCardParameters {\n const allowedCardNetworks = this.getPaymentMethod()\n .supportedCards.filter(isGooglePayCardNetworkKey)\n .map((key) => GooglePayCardNetwork[key]);\n\n return {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks,\n billingAddressRequired: true,\n billingAddressParameters: {\n format: 'FULL',\n phoneNumberRequired: true,\n },\n };\n }\n\n initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n this._getPaymentMethodFn = getPaymentMethod;\n this._isBuyNowFlow = Boolean(isBuyNowFlow);\n this._currencyCode = currencyCode;\n\n if (this._isBuyNowFlow) {\n this._getCurrencyCodeOrThrow();\n }\n\n return Promise.resolve();\n }\n\n async handleShippingAddressChange(\n shippingAddress?: GooglePayFullBillingAddress,\n ): Promise {\n if (shippingAddress) {\n shippingAddress.name = shippingAddress.name || '';\n shippingAddress.address1 = shippingAddress.address1 || '';\n }\n\n const mappedShippingAddress = this.mapToShippingAddressRequestBody({\n shippingAddress,\n } as GooglePayCardDataResponse);\n\n if (mappedShippingAddress) {\n await this._paymentIntegrationService.updateShippingAddress(mappedShippingAddress);\n }\n\n const state = this._paymentIntegrationService.getState();\n const consignments = state.getConsignments();\n\n if (!consignments?.[0]) {\n // Info: we can not return an empty data because shippingOptions should contain at least one element, it caused a developer exception\n return;\n }\n\n const consignment = consignments[0];\n const storeConfig = state.getStoreConfigOrThrow();\n\n if (!this._currencyService) {\n this._currencyService = createCurrencyService(storeConfig);\n }\n\n const availableShippingOptions = (consignment.availableShippingOptions || []).map(\n this._getGooglePayShippingOption.bind(this),\n );\n\n const recommendedShippingOption = consignment.availableShippingOptions?.find(\n (shippingOption) => shippingOption.isRecommended,\n );\n\n if (availableShippingOptions.length) {\n const selectedShippingOptionId =\n consignment.selectedShippingOption?.id ||\n recommendedShippingOption?.id ||\n availableShippingOptions[0]?.id;\n\n if (!consignment.selectedShippingOption?.id && availableShippingOptions[0]) {\n await this.handleShippingOptionChange(\n recommendedShippingOption?.id || availableShippingOptions[0].id,\n );\n }\n\n return {\n defaultSelectedOptionId: selectedShippingOptionId,\n shippingOptions: availableShippingOptions,\n };\n }\n }\n\n async handleShippingOptionChange(optionId: string) {\n if (optionId === 'shipping_option_unselected') {\n return;\n }\n\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n getTotalPrice(): string {\n const { getCheckoutOrThrow, getCartOrThrow } = this._paymentIntegrationService.getState();\n const { decimalPlaces } = getCartOrThrow().currency;\n const totalPrice = round(getCheckoutOrThrow().outstandingBalance, decimalPlaces).toFixed(\n decimalPlaces,\n );\n\n return totalPrice;\n }\n\n protected getGooglePayInitializationData(): GooglePayInitializationData {\n return guard(\n this.getPaymentMethod().initializationData,\n () => new InvalidArgumentError('Missing initialization data.'),\n );\n }\n\n protected getPaymentMethod(): PaymentMethod {\n return guard(\n this._getPaymentMethodFn,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n )();\n }\n\n protected getGatewayIdentifier(): string {\n return this._gatewayIdentifier;\n }\n\n protected setGatewayIdentifier(gateway?: string) {\n this._gatewayIdentifier = gateway || this.getGatewayIdentifier();\n }\n\n private _isShippingAddressRequired(): boolean {\n const { getCartOrThrow, getStoreConfig, getShippingAddress } =\n this._paymentIntegrationService.getState();\n\n return (\n getShippingAddress() === undefined &&\n itemsRequireShipping(getCartOrThrow(), getStoreConfig())\n );\n }\n\n private _mapToAddressRequestBody(\n address: GooglePayFullBillingAddress,\n company: string,\n phone: string,\n ): AddressRequestBody {\n const {\n name,\n address1,\n address2,\n address3,\n locality: city,\n administrativeArea: stateOrProvinceCode,\n countryCode,\n postalCode,\n phoneNumber,\n } = address;\n const [firstName, lastName] = this._getFirstAndLastName(name);\n\n return {\n firstName,\n lastName,\n company,\n address1,\n address2: `${address2} ${address3}`.trim(),\n city: city || stateOrProvinceCode,\n stateOrProvince: stateOrProvinceCode,\n stateOrProvinceCode,\n countryCode,\n postalCode,\n phone: phoneNumber || phone,\n customFields: [],\n };\n }\n\n private _getFirstAndLastName(fullName: string): [string, string] {\n const nameParts = fullName.split(' ');\n\n if (nameParts.length === 1) {\n return [fullName, ''];\n }\n\n const firstName = nameParts.slice(0, -1).join(' ');\n const lastName = nameParts[nameParts.length - 1];\n\n return [firstName, lastName];\n }\n\n private _getCurrencyCodeOrThrow(): string {\n return guard(\n this._currencyCode,\n () =>\n new InvalidArgumentError(\n 'Unable to initialize payment because \"options.currencyCode\" argument is not provided.',\n ),\n );\n }\n\n private _getGooglePayShippingOption({ id, cost, description }: ShippingOption) {\n const formattedCost = this._currencyService?.toCustomerCurrency(cost);\n\n return {\n id,\n label: description,\n description: formattedCost || cost,\n };\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * param config - The config object containing the currency configuration\n * returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import { GooglePayErrorObject } from '../types';\n\nexport default function isGooglePayErrorObject(error: unknown): error is GooglePayErrorObject {\n return typeof error === 'object' && error !== null && 'statusCode' in error;\n}\n","/**\n * A set of options that are required to initialize the GooglePay payment method\n *\n * If the customer chooses to pay with GooglePay, they will be asked to\n * enter their payment details via a modal. You can hook into events emitted by\n * the modal by providing the callbacks listed below.\n *\n * ```html\n * \n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * // Using GooglePay provided by Braintree as an example\n * methodId: 'googlepaybraintree',\n * googlepaybraintree: {\n * walletButton: 'wallet-button'\n * },\n * });\n * ```\n *\n * Additional event callbacks can be registered.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'googlepaybraintree',\n * googlepaybraintree: {\n * walletButton: 'wallet-button',\n * onError(error) {\n * console.log(error);\n * },\n * onPaymentSelect() {\n * console.log('Selected');\n * },\n * },\n * });\n * ```\n */\nexport default interface GooglePayPaymentInitializeOptions {\n /**\n * This walletButton is used to set an event listener, provide an element ID if you want\n * users to be able to launch the GooglePay wallet modal by clicking on a button.\n * It should be an HTML element.\n */\n walletButton?: string;\n\n /**\n * A callback that gets called when GooglePay fails to initialize or\n * selects a payment option.\n *\n * @param error - The error object describing the failure.\n */\n onError?(error: Error): void;\n\n /**\n * A callback that gets called when the customer selects a payment option.\n */\n onPaymentSelect?(): void;\n}\n\n/**\n * The recognized keys to pass the initialization options for Google Pay.\n */\nexport enum GooglePayKey {\n ADYEN_V2 = 'googlepayadyenv2',\n ADYEN_V3 = 'googlepayadyenv3',\n AUTHORIZE_NET = 'googlepayauthorizenet',\n BNZ = 'googlepaybnz',\n BRAINTREE = 'googlepaybraintree',\n PAYPAL_COMMERCE = 'googlepaypaypalcommerce',\n CHECKOUT_COM = 'googlepaycheckoutcom',\n CYBERSOURCE_V2 = 'googlepaycybersourcev2',\n ORBITAL = 'googlepayorbital',\n STRIPE = 'googlepaystripe',\n STRIPE_UPE = 'googlepaystripeupe',\n WORLDPAY_ACCESS = 'googlepayworldpayaccess',\n TD_ONLINE_MART = 'googlepaytdonlinemart',\n}\n\n/**\n * The options that are required to initialize the GooglePay payment method.\n * They can be omitted unless you need to support GooglePay.\n */\nexport type WithGooglePayPaymentInitializeOptions = {\n [k in GooglePayKey]?: GooglePayPaymentInitializeOptions;\n};\n","import { GooglePayKey } from '../google-pay-payment-initialize-options';\n\nexport default function isGooglePayKey(key: string): key is GooglePayKey {\n return Object.values(GooglePayKey).includes(key);\n}\n","import {\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n guard,\n InvalidArgumentError,\n NotImplementedError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCustomerInitializeOptions, {\n WithGooglePayCustomerInitializeOptions,\n} from './google-pay-customer-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayCustomerStrategy implements CustomerStrategy {\n private _paymentButton?: HTMLElement;\n private _methodId?: keyof WithGooglePayCustomerInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options?: CustomerInitializeOptions & WithGooglePayCustomerInitializeOptions,\n ): Promise {\n if (!options?.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n const googlePayOptions = options[this._getMethodId()];\n\n if (!googlePayOptions) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n let state = this._paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodId());\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodId());\n }\n\n try {\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(paymentMethod.initializationData?.storeCountry),\n );\n } catch {\n return;\n }\n\n this._addPaymentButton(googlePayOptions);\n }\n\n signIn(): Promise {\n return Promise.reject(\n new NotImplementedError(\n 'In order to sign in via Google Pay, the shopper must click on \"Google Pay\" button.',\n ),\n );\n }\n\n async signOut(): Promise {\n const providerId = this._paymentIntegrationService.getState().getPaymentId()?.providerId;\n\n if (providerId) {\n await this._googlePayPaymentProcessor.signOut(providerId);\n }\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n this._paymentButton?.remove();\n this._paymentButton = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n private _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n }: IntermediatePaymentData): Promise => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n } = this._googlePayPaymentProcessor.getCallbackTriggers();\n\n if (!availableTriggers.includes(callbackTrigger)) {\n return;\n }\n\n const availableShippingOptions = addressChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleShippingAddressChange(\n shippingAddress,\n )\n : undefined;\n\n if (shippingOptionsChangeTriggers.includes(callbackTrigger)) {\n await this._googlePayPaymentProcessor.handleShippingOptionChange(\n shippingOptionData.id,\n );\n }\n\n await this._paymentIntegrationService.loadCheckout();\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n },\n },\n };\n }\n\n private _addPaymentButton({\n container,\n buttonColor,\n buttonType,\n onClick,\n onError,\n }: GooglePayCustomerInitializeOptions): void {\n this._paymentButton =\n this._paymentButton ??\n this._googlePayPaymentProcessor.addPaymentButton(container, {\n buttonColor: buttonColor ?? 'default',\n buttonType: buttonType ?? 'plain',\n onClick: this._handleClick(onError, onClick),\n });\n }\n\n private _handleClick(\n onError: GooglePayCustomerInitializeOptions['onError'],\n onClick: GooglePayCustomerInitializeOptions['onClick'],\n ): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n if (onClick && typeof onClick === 'function') {\n onClick();\n }\n\n // TODO: Dispatch Widget Actions\n try {\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n };\n }\n\n private async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n const shippingAddress =\n this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(response);\n const siteLink =\n window.location.pathname === '/embedded-checkout'\n ? this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink\n : undefined;\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress) {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutForm(\n this._getMethodId(),\n response,\n siteLink,\n );\n }\n\n private _getMethodId(): keyof WithGooglePayCustomerInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n AddressRequestBody,\n BillingAddressRequestBody,\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethod,\n PaymentMethodFailedError,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from './gateways/google-pay-gateway';\nimport GooglePayScriptLoader from './google-pay-script-loader';\nimport isGooglePayAdditionalActionProcessable from './guards/is-google-pay-additional-action-processable';\nimport {\n GooglePayBaseCardPaymentMethod,\n GooglePayButtonOptions,\n GooglePayCardDataResponse,\n GooglePayCardPaymentMethod,\n GooglePayFullBillingAddress,\n GooglePayGatewayBaseRequest,\n GooglePayInitializationData,\n GooglePayIsReadyToPayRequest,\n GooglePaymentsClient,\n GooglePayPaymentDataRequest,\n GooglePayPaymentOptions,\n ShippingOptionParameters,\n} from './types';\n\nexport default class GooglePayPaymentProcessor {\n private _paymentsClient?: GooglePaymentsClient;\n private _baseRequest: GooglePayGatewayBaseRequest = { apiVersion: 2, apiVersionMinor: 0 };\n private _baseCardPaymentMethod?: GooglePayBaseCardPaymentMethod;\n private _cardPaymentMethod?: GooglePayCardPaymentMethod;\n private _paymentDataRequest?: GooglePayPaymentDataRequest;\n private _isReadyToPayRequest?: GooglePayIsReadyToPayRequest;\n\n constructor(\n private _scriptLoader: GooglePayScriptLoader,\n private _gateway: GooglePayGateway,\n private _requestSender: RequestSender,\n private _formPoster: FormPoster,\n ) {}\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n googlePayPaymentOptions?: GooglePayPaymentOptions,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n this._paymentsClient = await this._scriptLoader.getGooglePaymentsClient(\n getPaymentMethod().config.testMode,\n googlePayPaymentOptions,\n );\n\n await this._gateway.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n this._buildButtonPayloads();\n }\n\n async initializeWidget() {\n await this._buildWidgetPayloads();\n\n await this._determineReadinessToPay();\n\n this._prefetchGooglePaymentData();\n }\n\n getNonce(methodId: string) {\n return this._gateway.getNonce(methodId);\n }\n\n async extraPaymentData() {\n return this._gateway.extraPaymentData();\n }\n\n addPaymentButton(\n containerId: string,\n options: Omit,\n ): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Google Pay button to an invalid HTML container element.',\n );\n }\n\n const paymentButton = this._getPaymentsClient().createButton({\n ...options,\n allowedPaymentMethods: [this._getBaseCardPaymentMethod()],\n });\n\n return container.appendChild(paymentButton);\n }\n\n async showPaymentSheet(): Promise {\n const paymentDataRequest = this._getPaymentDataRequest();\n\n return this._getPaymentsClient().loadPaymentData(paymentDataRequest);\n }\n\n async setExternalCheckoutXhr(\n provider: string,\n response: GooglePayCardDataResponse,\n ): Promise {\n return this._setExternalCheckout(provider, response);\n }\n\n async setExternalCheckoutForm(\n provider: string,\n response: GooglePayCardDataResponse,\n siteLink?: string,\n ): Promise {\n return this._setExternalCheckout(provider, response, true, siteLink);\n }\n\n mapToBillingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): BillingAddressRequestBody | undefined {\n return this._gateway.mapToBillingAddressRequestBody(response);\n }\n\n mapToShippingAddressRequestBody(\n response: GooglePayCardDataResponse,\n ): AddressRequestBody | undefined {\n return this._gateway.mapToShippingAddressRequestBody(response);\n }\n\n processAdditionalAction(error: unknown, methodId?: string): Promise {\n return isGooglePayAdditionalActionProcessable(this._gateway)\n ? this._gateway.processAdditionalAction(error, methodId)\n : Promise.reject(error);\n }\n\n async signOut(providerId: string): Promise {\n await this._requestSender.get(`/remote-checkout/${providerId}/signout`);\n }\n\n getCallbackTriggers() {\n return this._gateway.getCallbackTriggers();\n }\n\n async handleShippingAddressChange(\n shippingAddress: GooglePayFullBillingAddress,\n ): Promise {\n return this._gateway.handleShippingAddressChange(shippingAddress);\n }\n\n async handleShippingOptionChange(optionId: string): Promise {\n await this._gateway.handleShippingOptionChange(optionId);\n }\n\n getTotalPrice(): string {\n return this._gateway.getTotalPrice();\n }\n\n async _setExternalCheckout(\n provider: string,\n response: GooglePayCardDataResponse,\n useFormPoster = false,\n siteLink?: string,\n ): Promise {\n const url = '/checkout.php';\n const body = {\n action: 'set_external_checkout',\n provider,\n ...(await this._gateway.mapToExternalCheckoutData(response)),\n };\n\n if (useFormPoster) {\n return new Promise((resolve) => {\n this._formPoster.postForm(\n siteLink ? `${siteLink}/checkout` : url,\n {\n ...body,\n card_information: JSON.stringify(body.card_information),\n },\n resolve,\n );\n });\n }\n\n await this._requestSender.post(url, {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body,\n });\n }\n\n private _prefetchGooglePaymentData(): void {\n const paymentDataRequest = this._getPaymentDataRequest();\n\n paymentDataRequest.transactionInfo = this._gateway.getTransactionInfo();\n\n this._getPaymentsClient().prefetchPaymentData(paymentDataRequest);\n }\n\n private async _determineReadinessToPay(): Promise {\n try {\n const { result } = await this._getPaymentsClient().isReadyToPay(\n this._getIsReadyToPayRequest(),\n );\n\n if (result === false) {\n throw new PaymentMethodFailedError(\n 'Google Pay is not supported by the current device and browser, please try another payment method.',\n );\n }\n } catch (error) {\n if (error instanceof PaymentMethodFailedError) {\n throw error;\n }\n\n throw new PaymentMethodFailedError();\n }\n }\n\n private _buildButtonPayloads() {\n this._baseCardPaymentMethod = {\n type: 'CARD',\n parameters: this._gateway.getCardParameters(),\n };\n }\n\n private async _buildWidgetPayloads(): Promise {\n const baseCardPaymentMethod = this._getBaseCardPaymentMethod();\n\n this._cardPaymentMethod = {\n ...baseCardPaymentMethod,\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: await this._gateway.getPaymentGatewayParameters(),\n },\n };\n this._paymentDataRequest = {\n ...this._baseRequest,\n allowedPaymentMethods: [this._cardPaymentMethod],\n transactionInfo: this._gateway.getTransactionInfo(),\n merchantInfo: this._gateway.getMerchantInfo(),\n ...(await this._gateway.getRequiredData()),\n callbackIntents: this._gateway.getCallbackIntents(),\n };\n this._isReadyToPayRequest = {\n ...this._baseRequest,\n allowedPaymentMethods: [baseCardPaymentMethod],\n };\n }\n\n private _getBaseCardPaymentMethod(): GooglePayBaseCardPaymentMethod {\n return this._getOrThrow(this._baseCardPaymentMethod);\n }\n\n private _getPaymentDataRequest(): GooglePayPaymentDataRequest {\n return this._getOrThrow(this._paymentDataRequest);\n }\n\n private _getIsReadyToPayRequest(): GooglePayIsReadyToPayRequest {\n return this._getOrThrow(this._isReadyToPayRequest);\n }\n\n private _getPaymentsClient(): GooglePaymentsClient {\n return this._getOrThrow(this._paymentsClient);\n }\n\n private _getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","import GooglePayGateway from '../gateways/google-pay-gateway';\nimport { GooglePayAdditionalActionProcessable } from '../types';\n\nexport default function isGooglePayAdditionalActionProcessable(\n gateway: GooglePayGateway,\n): gateway is GooglePayGateway & GooglePayAdditionalActionProcessable {\n return 'processAdditionalAction' in gateway;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayHostWindow, GooglePaymentsClient, GooglePayPaymentOptions } from './types';\n\nexport const GOOGLE_PAY_LIBRARY = 'https://pay.google.com/gp/p/js/pay.js';\n\nexport default class GooglePayScriptLoader {\n private _paymentsClient?: GooglePaymentsClient;\n private _window: GooglePayHostWindow = window;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async getGooglePaymentsClient(\n testMode = false,\n options?: GooglePayPaymentOptions,\n ): Promise {\n await this._scriptLoader.loadScript(GOOGLE_PAY_LIBRARY);\n\n if (!this._window.google) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n if (this._paymentsClient === undefined) {\n this._paymentsClient = new this._window.google.payments.api.PaymentsClient({\n environment: testMode ? 'TEST' : 'PRODUCTION',\n ...(options ?? {}),\n });\n }\n\n return this._paymentsClient;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport GooglePayScriptLoader from '../google-pay-script-loader';\n\nexport default function createGooglePayScriptLoader() {\n return new GooglePayScriptLoader(getScriptLoader());\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV2CustomerStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3CustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV3CustomerStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertsIsGooglePayAuthorizeNetInitializationData from '../guards/is-google-pay-authorizenet-initialization-data';\nimport {\n GooglePayCardDataResponse,\n GooglePayGatewayParameters,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAuthorizeNetGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('authorizenet', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayAuthorizeNetInitializationData(data);\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId: data.paymentGatewayId,\n };\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayAuthorizeNetInitializationData, GooglePayInitializationData } from '../types';\n\nfunction isGooglePayAuthorizeNetInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayAuthorizeNetInitializationData {\n return 'paymentGatewayId' in data;\n}\n\nexport default function assertsIsGooglePayAuthorizeNetInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayAuthorizeNetInitializationData {\n if (!isGooglePayAuthorizeNetInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeDotNetCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAuthorizeDotNetCustomerStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import RequestError from './request-error';\n\n// Have to use `as` https://stackoverflow.com/questions/73987044/typeguarding-an-unknown-nested-object should be fixed in 4.8+\nconst isRequestError = (error: unknown): error is RequestError => {\n return typeof error === 'object' && error !== null && 'body' in error;\n};\n\nexport default isRequestError;\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCheckoutComInitializationData, GooglePayInitializationData } from '../types';\n\nfunction isGooglePayCheckoutComInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayCheckoutComInitializationData {\n return 'checkoutcomkey' in data;\n}\n\nexport default function assertIsGooglePayCheckoutComInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayCheckoutComInitializationData {\n if (!isGooglePayCheckoutComInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n InvalidArgumentError,\n isRequestError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertIsGooglePayCheckoutComInitializationData from '../guards/is-google-pay-checkoutcom-initialization-data';\nimport { isGooglePayThreeDSecureResult } from '../guards/is-google-pay-threedsecure-result';\nimport assertIsGooglePayTokenObject from '../guards/is-google-pay-token-object';\nimport {\n GooglePayAdditionalActionProcessable,\n GooglePayCardDataResponse,\n GooglePayCheckoutComTokenObject,\n GooglePayGatewayParameters,\n GooglePaySetExternalCheckoutData,\n GooglePayTokenObject,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayCheckoutComGateway\n extends GooglePayGateway\n implements GooglePayAdditionalActionProcessable\n{\n constructor(service: PaymentIntegrationService, private _requestSender: RequestSender) {\n super('checkoutltd', service);\n }\n\n processAdditionalAction(error: unknown): Promise {\n return new Promise((_resolve, reject) => {\n if (\n isRequestError(error) &&\n isGooglePayThreeDSecureResult(error.body) &&\n error.body.three_ds_result.code === 'three_d_secure_required'\n ) {\n return window.location.assign(error.body.three_ds_result.acs_url);\n }\n\n reject(error);\n });\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayTokenObject(token);\n\n data.nonce = await this._tokenize(token);\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertIsGooglePayCheckoutComInitializationData(data);\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId: data.checkoutcomkey,\n };\n }\n\n private async _tokenize(token_data: GooglePayTokenObject): Promise {\n const url = this.getPaymentMethod().config.testMode\n ? 'https://api.sandbox.checkout.com/tokens'\n : 'https://api.checkout.com/tokens';\n const data = this.getGooglePayInitializationData();\n\n assertIsGooglePayCheckoutComInitializationData(data);\n\n const { body } = await this._requestSender.post(url, {\n credentials: false,\n body: {\n type: 'googlepay',\n token_data,\n },\n headers: {\n Authorization: data.checkoutcomkey,\n 'Content-Type': ContentType.Json,\n 'X-XSRF-TOKEN': null,\n },\n });\n\n return body.token;\n }\n}\n","import { RequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayThreeDSecureResult } from '../types';\n\nexport function isGooglePayThreeDSecureResult(\n body: RequestError['body'],\n): body is GooglePayThreeDSecureResult {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n\n const threeDSBody = body as Partial;\n\n return (\n typeof threeDSBody.three_ds_result?.acs_url === 'string' &&\n typeof threeDSBody.three_ds_result.code === 'string'\n );\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayTokenObject } from '../types';\n\nfunction isGooglePayTokenObject(token: unknown): token is GooglePayTokenObject {\n return (\n typeof token === 'object' &&\n token !== null &&\n 'protocolVersion' in token &&\n 'signature' in token &&\n 'signedMessage' in token\n );\n}\n\nexport default function assertIsGooglePayTokenObject(\n token: unknown,\n): asserts token is GooglePayTokenObject {\n if (!isGooglePayTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComCustomerStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayCybersourceGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('cybersource', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourceCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCybersourceCustomerStrategy, [\n { id: 'googlepaycybersourcev2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBnzCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBnzCustomerStrategy, [{ id: 'googlepaybnz' }]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayOrbitalGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('chase', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayOrbitalCustomerStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import InvalidArgumentError from './invalid-argument-error';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData, GooglePayStripeInitializationData } from '../types';\n\nfunction isGooglePayStripeInitializationData(\n data: GooglePayInitializationData,\n): data is GooglePayStripeInitializationData {\n return (\n 'stripeConnectedAccount' in data &&\n 'stripePublishableKey' in data &&\n 'stripeVersion' in data\n );\n}\n\nexport default function assertsIsGooglePayStripeInitializationData(\n data: GooglePayInitializationData,\n): asserts data is GooglePayStripeInitializationData {\n if (!isGooglePayStripeInitializationData(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { includes, some } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isRequestError,\n PaymentArgumentInvalidError,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../gateways/google-pay-gateway';\nimport assertsIsGooglePayStripeInitializationData from '../guards/is-google-pay-stripe-initialization-data';\nimport isGooglePayStripeRequestError from '../guards/is-google-pay-stripe-request-error';\nimport assertIsGooglePayStripeTokenObject from '../guards/is-google-pay-stripe-token-object';\nimport {\n GooglePayCardDataResponse,\n GooglePaySetExternalCheckoutData,\n GooglePayStripeGatewayParameters,\n} from '../types';\n\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\nimport { StripeError, StripeUPEClient } from './types';\n\nexport default class GooglePayStripeGateway extends GooglePayGateway {\n private stripeUPEClient?: StripeUPEClient;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {\n super('stripe', paymentIntegrationService);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayStripeTokenObject(token);\n\n data.nonce = token.id;\n\n return data;\n }\n\n getPaymentGatewayParameters(): GooglePayStripeGatewayParameters {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(data);\n\n const { stripeVersion, stripePublishableKey, stripeConnectedAccount } = data;\n\n return {\n gateway: this.getGatewayIdentifier(),\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n };\n }\n\n async processAdditionalAction(\n error: unknown,\n methodId?: string,\n ): Promise {\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!isRequestError(error) || !isGooglePayStripeRequestError(error.body)) {\n throw error;\n }\n\n const state = this.paymentIntegrationService.getState();\n const isStripeGooglePay3dsExperimentIsOn =\n state.getStoreConfig()?.checkoutSettings.features[\n 'STRIPE-476.enable_stripe_googlepay_3ds'\n ];\n const shouldTrigger3DS =\n some(error.body.errors, { code: 'three_d_secure_required' }) &&\n isStripeGooglePay3dsExperimentIsOn;\n\n if (shouldTrigger3DS) {\n const data = this.getGooglePayInitializationData();\n\n assertsIsGooglePayStripeInitializationData(data);\n\n const { stripePublishableKey, stripeConnectedAccount } = data;\n\n this.stripeUPEClient = await this.loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this.stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (_) {\n try {\n result = await this.stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (__) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n return this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: { nonce: result?.paymentIntent?.id || clientSecret },\n });\n }\n\n throw error;\n }\n\n private async loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayStripeTokenObject } from '../types';\n\nfunction isGooglePayStripeTokenObject(token: unknown): token is GooglePayStripeTokenObject {\n return typeof token === 'object' && token !== null && 'id' in token;\n}\n\nexport default function assertIsGooglePayStripeTokenObject(\n token: unknown,\n): asserts token is GooglePayStripeTokenObject {\n if (!isGooglePayStripeTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","interface AdditionalActionError {\n three_ds_result: { token: string };\n errors: Array<{ code: string }>;\n}\n\nconst isGooglePayStripeRequestError = (body: unknown): body is AdditionalActionError => {\n return (\n typeof body === 'object' && body !== null && 'three_ds_result' in body && 'errors' in body\n );\n};\n\nexport default isGooglePayStripeRequestError;\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripeHostWindow, StripeUPEClient } from './types';\n\nexport default class StripeUPEScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this.stripeWindow.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n private async load() {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript('https://js.stripe.com/v3/');\n }\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.stripeWindow.Stripe;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeCustomerStrategy, [\n { id: 'googlepaystripe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeUpeCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayStripeUpeCustomerStrategy, [\n { id: 'googlepaystripeupe' },\n]);\n","import { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayCardDataResponse, GooglePaySetExternalCheckoutData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayWorldpayAccessGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService) {\n super('worldpay', service);\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayWorldpayAccessCustomerStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","export default class CancellablePromise {\n promise: Promise;\n cancel!: (reason?: any) => void;\n\n constructor(promise: Promise) {\n const cancellable = new Promise((_, reject) => {\n this.cancel = reject;\n });\n\n this.promise = Promise.race([promise, cancellable]);\n }\n}\n","import {\n BraintreeGooglePayment,\n BraintreeGooglePayThreeDSecure,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CancellablePromise,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertIsGooglePayBraintreeTokenObject from '../guards/is-google-pay-braintree-token-object';\nimport {\n GooglePayCardDataResponse,\n GooglePayGatewayParameters,\n GooglePayInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayBraintreeGateway extends GooglePayGateway {\n private _braintreeGooglePayment?: BraintreeGooglePayment;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _braintreeSdk: BraintreeSdk) {\n super('braintree', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.clientToken || !paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeSdk.initialize(paymentMethod.clientToken);\n this._braintreeGooglePayment = await this._braintreeSdk.getBraintreeGooglePayment();\n\n return Promise.resolve();\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n\n const { clientToken, initializationData } = super.getPaymentMethod();\n\n if (!clientToken || !initializationData || !initializationData.card_information?.bin) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n isThreeDSecureEnabled,\n card_information: { bin, isNetworkTokenized },\n } = initializationData;\n\n if (isThreeDSecureEnabled && !isNetworkTokenized) {\n const threeDSecure = await this._braintreeSdk.getBraintreeThreeDS();\n\n const { orderAmount } = this._service.getState().getOrderOrThrow();\n\n const verification = await this._braintreePresent3DSChallenge(\n threeDSecure,\n orderAmount,\n nonce,\n bin,\n );\n\n return verification.nonce;\n }\n\n return nonce;\n }\n\n async extraPaymentData() {\n return {\n deviceSessionId: await this._getBraintreeDeviceData(),\n };\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n let token: unknown;\n\n try {\n token = JSON.parse(data.nonce);\n } catch (error) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n assertIsGooglePayBraintreeTokenObject(token);\n\n data.nonce = token.androidPayCards[0].nonce;\n data.card_information.bin = token.androidPayCards[0].details.bin;\n data.card_information.isNetworkTokenized =\n token.androidPayCards[0].details.isNetworkTokenized;\n\n return data;\n }\n\n getCardParameters() {\n return super.getCardParameters();\n }\n\n async getPaymentGatewayParameters(): Promise {\n const braintreeGooglePayment = this.getBraintreeGooglePayment();\n\n const request = braintreeGooglePayment.createPaymentDataRequest({\n merchantInfo: super.getMerchantInfo(),\n transactionInfo: super.getTransactionInfo(),\n cardRequirements: {\n billingAddressRequired: true,\n billingAddressFormat: 'FULL',\n },\n ...(await super.getRequiredData()),\n });\n\n return request.paymentMethodTokenizationParameters.parameters;\n }\n\n private getBraintreeGooglePayment(): BraintreeGooglePayment {\n if (!this._braintreeGooglePayment) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._braintreeGooglePayment;\n }\n\n private async _getBraintreeDeviceData(): Promise {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n }\n\n private _braintreePresent3DSChallenge(\n threeDSecure: BraintreeGooglePayThreeDSecure,\n amount: number,\n nonce: string,\n bin: string,\n ) {\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n amount,\n bin,\n nonce,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayBraintreeTokenObject } from '../types';\n\nfunction isGooglePayBraintreeTokenObject(token: unknown): token is GooglePayBraintreeTokenObject {\n return typeof token === 'object' && token !== null && 'androidPayCards' in token;\n}\n\nexport default function assertIsGooglePayBraintreeTokenObject(\n token: unknown,\n): asserts token is GooglePayBraintreeTokenObject {\n if (!isGooglePayBraintreeTokenObject(token)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreePaymentStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreePaymentStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","import {\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../gateways/google-pay-gateway';\nimport assertsIsGooglePayPayPalCommercePaymentMethod from '../guards/is-google-pay-paypal-commerce-payment-method';\nimport {\n GooglePayCardDataResponse,\n GooglePayPayPalCommerceGatewayParameters,\n GooglePayPayPalCommerceInitializationData,\n GooglePaySetExternalCheckoutData,\n} from '../types';\n\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\nimport { GooglePayConfig } from './types';\n\nexport default class GooglePayPaypalCommerceGateway extends GooglePayGateway {\n private googlepayConfig?: GooglePayConfig;\n private service: PaymentIntegrationService;\n\n constructor(\n service: PaymentIntegrationService,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {\n super('paypalsb', service);\n\n this.service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n const currency = this.service.getState().getStoreConfig()?.currency.code ?? currencyCode;\n\n if (!currency) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n await super.initialize(getPaymentMethod, isBuyNowFlow, currency);\n\n const paymentMethod = super.getPaymentMethod();\n\n if (!paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n assertsIsGooglePayPayPalCommercePaymentMethod(paymentMethod);\n\n await this.paypalCommerceScriptLoader.getPayPalSDK(paymentMethod, currency);\n\n this.googlepayConfig = await this.paypalCommerceScriptLoader.getGooglePayConfigOrThrow();\n\n const { allowedPaymentMethods } = this.googlepayConfig;\n\n this.setGatewayIdentifier(\n allowedPaymentMethods[0]?.tokenizationSpecification?.parameters?.gateway,\n );\n }\n\n getPaymentGatewayParameters(): GooglePayPayPalCommerceGatewayParameters {\n if (this.googlepayConfig) {\n const { allowedPaymentMethods } = this.googlepayConfig;\n const { gatewayMerchantId } =\n allowedPaymentMethods[0].tokenizationSpecification.parameters;\n\n return {\n gateway: this.getGatewayIdentifier(),\n gatewayMerchantId,\n };\n }\n\n return {\n gateway: this.getGatewayIdentifier(),\n };\n }\n\n async mapToExternalCheckoutData(\n response: GooglePayCardDataResponse,\n ): Promise {\n const data = await super.mapToExternalCheckoutData(response);\n\n data.nonce = btoa(data.nonce);\n\n return data;\n }\n}\n","import {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nfunction isGooglePayPaypalCommercePaymentMethod(\n data: PaymentMethod,\n): data is PaymentMethod {\n if (data.initializationData) {\n return (\n 'attributionId' in data.initializationData &&\n 'isVenmoEnabled' in data.initializationData &&\n 'isGooglePayEnabled' in data.initializationData &&\n 'isPayPalCreditAvailable' in data.initializationData\n );\n }\n\n return false;\n}\n\nexport default function assertsIsGooglePayPayPalCommercePaymentMethod(\n data: PaymentMethod,\n): asserts data is PaymentMethod {\n if (!isGooglePayPaypalCommercePaymentMethod(data)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport {\n ComponentsScriptType,\n FundingType,\n GooglePayConfig,\n PayPalCommerceHostWindow,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './types';\n\nexport default class GooglePayPayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n private googlepayConfig?: GooglePayConfig;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.loadPayPalSDK(paypalSdkScriptConfig, forceLoad);\n }\n\n async getGooglePayConfigOrThrow() {\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n if (!this.googlepayConfig) {\n this.googlepayConfig = await this.window.paypal.Googlepay().config();\n }\n\n return this.googlepayConfig;\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const options = this.transformConfig(\n paypalSdkScriptConfig.options,\n );\n const attributes = this.transformConfig(\n paypalSdkScriptConfig.attributes,\n );\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(options).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes });\n }\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n isGooglePayEnabled,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: [\n 'buttons',\n 'hosted-fields',\n 'messages',\n 'payment-fields',\n 'legal',\n ...googlePayComponent,\n ...cardFieldsComponent,\n ],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayCustomerStrategy from '../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(\n paymentIntegrationService,\n new PayPalCommerceScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceCustomerStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n const { navigator } = window;\n\n let language: string;\n\n if (navigator.language) {\n language = navigator.language;\n } else {\n language = (navigator as any).userLanguage;\n }\n\n return {\n color_depth: window.screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language,\n screen_height: window.screen.height,\n screen_width: window.screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n getBrowserInfo,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isTdOnlineMartAdditionalAction } from '../guards/is-google-pay-td-online-mart-additional-action';\nimport { ExtraPaymentData, TdOnlineMartThreeDSErrorBody } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayTdOnlineMartGateway extends GooglePayGateway {\n constructor(service: PaymentIntegrationService, private formPoster: FormPoster) {\n super('worldlinena', service);\n }\n\n async extraPaymentData(): Promise {\n return Promise.resolve({ browser_info: getBrowserInfo() });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isTdOnlineMartAdditionalAction(error)) {\n throw error;\n }\n\n const { three_ds_result: threeDSResult }: TdOnlineMartThreeDSErrorBody = error.body;\n const {\n acs_url: formUrl,\n payer_auth_request: threeDSSessionData,\n merchant_data: creq,\n } = threeDSResult || {};\n\n if (!formUrl || !threeDSSessionData || !creq) {\n throw new PaymentArgumentInvalidError(['formUrl', 'threeDSSessionData', 'creq']);\n }\n\n return new Promise((resolve) => {\n this.formPoster.postForm(\n formUrl,\n {\n threeDSSessionData,\n creq,\n },\n resolve,\n '_top',\n );\n });\n }\n}\n","import { isArray, isObject, some } from 'lodash';\n\nimport { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TdOnlineMartAdditionalAction, TdOnlineMartThreeDSErrorBody } from '../types';\n\nfunction isTdOnlineMartThreeDSErrorBody(\n errorBody: unknown,\n): errorBody is TdOnlineMartThreeDSErrorBody {\n return (\n isObject(errorBody) &&\n typeof errorBody === 'object' &&\n 'errors' in errorBody &&\n 'three_ds_result' in errorBody &&\n isArray((errorBody as TdOnlineMartThreeDSErrorBody).errors) &&\n some((errorBody as TdOnlineMartThreeDSErrorBody).errors, {\n code: 'three_d_secure_required',\n })\n );\n}\n\nexport function isTdOnlineMartAdditionalAction(\n error: unknown,\n): error is TdOnlineMartAdditionalAction {\n return isRequestError(error) && isTdOnlineMartThreeDSErrorBody(error.body);\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayCustomerStrategy from '../../google-pay-customer-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartCustomerStrategy: CustomerStrategyFactory<\n GooglePayCustomerStrategy\n> = (paymentIntegrationService) =>\n new GooglePayCustomerStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartCustomerStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","export enum CartSource {\n BuyNow = 'BUY_NOW',\n}\n","import {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\nexport interface PayPalCommerceSDKFunding {\n CARD: string;\n PAYPAL: string;\n CREDIT: string;\n PAYLATER: string;\n OXXO: string;\n SEPA: string;\n VENMO: string;\n}\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\n\nexport interface PayPalCommerceCardFieldsConfig {\n inputEvents: {\n onChange(data: PayPalCommerceCardFieldsState): void;\n onFocus(data: PayPalCommerceCardFieldsState): void;\n onBlur(data: PayPalCommerceCardFieldsState): void;\n onInputSubmitRequest(data: PayPalCommerceCardFieldsState): void;\n };\n createVaultSetupToken?: (data: PayPalCommerceCardFieldsState) => void;\n createOrder?: () => Promise;\n style: PayPalCommerceHostedFieldsRenderOptions['styles'];\n onApprove(data: PayPalCommerceCardFieldsOnApproveData): void;\n onError(): void;\n}\n\nexport interface PayPalCommerceCardFieldsOnApproveData {\n vaultSetupToken?: string;\n orderID: string;\n liabilityShift?: LiabilityShiftEnum;\n}\n\nexport enum LiabilityShiftEnum {\n Possible = 'POSSIBLE',\n No = 'NO',\n Unknown = 'UNKNOWN',\n Yes = 'YES',\n}\n\ninterface PayPalCommerceCardFieldsFieldData {\n isFocused: boolean;\n isEmpty: boolean;\n isValid: boolean;\n isPotentiallyValid: boolean;\n}\n\ntype PayPalCommerceCardFieldsCard = PayPalCommerceHostedFieldsCard;\n\nexport interface PayPalCommerceCardFieldsState {\n cards: PayPalCommerceCardFieldsCard[];\n emittedBy: string;\n isFormValid: boolean;\n errors: string[];\n fields: {\n cardCvvField: PayPalCommerceCardFieldsFieldData;\n cardNumberField: PayPalCommerceCardFieldsFieldData;\n cardNameField?: PayPalCommerceCardFieldsFieldData;\n cardExpiryField: PayPalCommerceCardFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceFields {\n render(container: HTMLElement | string): Promise;\n clear(): void;\n removeClass(className: string): Promise;\n close(): Promise;\n}\n\ninterface PayPalCommerceFieldsInitializationData {\n placeholder?: string;\n}\n\nexport interface PayPalCommerceCardFields {\n isEligible(): boolean;\n CVVField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n ExpiryField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n NameField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n NumberField(config?: PayPalCommerceFieldsInitializationData): PayPalCommerceFields;\n submit(config?: PayPalCommerceCardFieldsSubmitConfig): Promise;\n getState(): Promise;\n}\n\nexport interface PayPalCommerceCardFieldsSubmitConfig {\n billingAddress: {\n company?: string;\n addressLine1: string;\n addressLine2?: string;\n adminArea1: string; // State\n adminArea2: string; // City\n postalCode: string;\n countryCode?: string;\n };\n}\n\nexport interface PayPalSDK {\n CardFields: (data: PayPalCommerceCardFieldsConfig) => Promise;\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (arg0: {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n }) => Promise<{ status: string }>;\n initiatePayerAction: () => void;\n };\n FUNDING: PayPalCommerceSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(data: PayPalCommerceHostedFieldsRenderOptions): Promise;\n };\n Legal: PayPalLegal & LegalFunding;\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n Messages(options: PayPalCommerceMessagesOptions): PayPalCommerceMessages;\n}\n\nexport interface ConfirmOrderData {\n tokenizationData: {\n type: string;\n token: string;\n };\n info: {\n cardNetwork: string;\n cardDetails: string;\n };\n type: string;\n}\n\nexport interface GooglePayConfig {\n allowedPaymentMethods: AllowedPaymentMethods[];\n apiVersion: number;\n apiVersionMinor: number;\n countryCode: string;\n isEligible: boolean;\n merchantInfo: {\n merchantId: string;\n merchantOrigin: string;\n };\n}\n\nexport interface AllowedPaymentMethods {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n billingAddressRequired: boolean;\n assuranceDetailsRequired: boolean;\n billingAddressParameters: {\n format: string;\n };\n };\n tokenizationSpecification: {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId: string;\n };\n };\n}\n\nexport type PayPalLegal = (params: { fundingSource: string }) => {\n render(container: string): void;\n};\n\nexport interface LegalFunding {\n FUNDING: {\n PAY_UPON_INVOICE: string;\n };\n}\n\nexport interface BirthDate {\n getFullYear(): number;\n getDate(): number;\n getMonth(): number;\n}\n\nexport interface PayPalCommerceScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-user-id-token'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n | 'buttons'\n | 'funding-eligibility'\n | 'hosted-fields'\n | 'messages'\n | 'payment-fields'\n | 'legal'\n | 'googlepay'\n | 'connect'\n | 'card-fields'\n>;\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalLoadScript?: (options: PayPalCommerceScriptParams) => Promise<{ paypal: PayPalSDK }>;\n}\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isAcceleratedCheckoutEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n shouldRunAcceleratedCheckout?: boolean;\n paymentButtonStyles?: Record;\n}\n\n/**\n *\n * PayPal Commerce BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Commerce Hosted Fields\n *\n */\nexport interface PayPalCommerceHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalCommerceHostedFieldOption;\n cvv?: PayPalCommerceHostedFieldOption;\n expirationDate?: PayPalCommerceHostedFieldOption;\n };\n paymentsSDK?: boolean;\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n createOrder(): Promise;\n}\n\nexport interface PayPalCommerceHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalCommerceHostedFields {\n submit(\n options?: PayPalCommerceHostedFieldsSubmitOptions,\n ): Promise;\n getState(): PayPalCommerceHostedFieldsState;\n on(eventName: string, callback: (event: PayPalCommerceHostedFieldsState) => void): void;\n}\n\nexport interface PayPalCommerceHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalCommerceHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalCommerceHostedFieldsState {\n cards: PayPalCommerceHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalCommerceHostedFieldsFieldData;\n expirationDate?: PayPalCommerceHostedFieldsFieldData;\n expirationMonth?: PayPalCommerceHostedFieldsFieldData;\n expirationYear?: PayPalCommerceHostedFieldsFieldData;\n cvv?: PayPalCommerceHostedFieldsFieldData;\n postalCode?: PayPalCommerceHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n experience?: string;\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n ): Promise | void;\n onInit?(data: InitCallbackPayload, actions: InitCallbackActions): Promise;\n onComplete?(data: CompleteCallbackDataPayload): Promise;\n onClick?(data: ClickCallbackPayload, actions: ClickCallbackActions): Promise | void;\n onError?(error: Error): void;\n onCancel?(): void;\n onShippingAddressChange?(data: ShippingAddressChangeCallbackPayload): Promise;\n onShippingOptionsChange?(data: ShippingOptionChangeCallbackPayload): Promise;\n}\n\nexport interface ShippingOptionChangeCallbackPayload {\n orderId: string;\n selectedShippingOption: PayPalSelectedShippingOption;\n}\n\nexport interface ShippingAddressChangeCallbackPayload {\n orderId: string;\n shippingAddress: PayPalAddress;\n}\n\nexport interface ClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface ClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface InitCallbackPayload {\n correlationID: string;\n}\n\nexport interface InitCallbackActions {\n disable(): void;\n enable(): void;\n}\n\nexport interface PayPalAddress {\n city: string;\n countryCode: string;\n postalCode: string;\n state: string;\n}\n\nexport interface PaypalAddressCallbackData {\n city: string;\n country_code: string;\n postal_code: string;\n state: string;\n}\n\nexport interface PayPalSelectedShippingOption {\n amount: {\n currency_code: string;\n value: string;\n };\n id: string;\n label: string;\n selected: boolean;\n type: string;\n}\n\nexport interface ApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface ApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n name: {\n full_name: string;\n };\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n address_line_2: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport interface CompleteCallbackDataPayload {\n intent: string;\n orderID: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayPalCommerce Messages\n */\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessages {\n render(id: string): void;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalCommerceMessagesStyleOptions;\n fundingSource?: string;\n}\n\n// TODO: This interface can be removed once the PayPaySDK interface is removed\nexport interface PayPalCommerceMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Other\n *\n */\nexport enum NonInstantAlternativePaymentMethods {\n OXXO = 'oxxo',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n setupToken?: string;\n approveUrl: string;\n}\n\nexport interface PayPalUpdateOrderRequestBody {\n availableShippingOptions?: ShippingOption[];\n cartId: string;\n selectedShippingOption?: ShippingOption;\n}\n\nexport interface PayPalUpdateOrderResponse {\n statusCode: number;\n}\n\nexport interface PayPalCreateOrderRequestBody extends HostedInstrument, VaultedInstrument {\n cartId: string;\n metadataId?: string;\n setupToken?: boolean;\n}\n\nexport enum PayPalOrderStatus {\n Approved = 'APPROVED',\n Created = 'CREATED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n PollingStop = 'POLLING_STOP',\n PollingError = 'POLLING_ERROR',\n}\n\nexport interface PayPalOrderStatusData {\n status: PayPalOrderStatus;\n}\n\nexport interface PayPalCreateOrderCardFieldsResponse {\n orderId: string;\n setupToken?: string;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n BillingAddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n CartSource,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n RequestError,\n RequestOptions,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceRequestSender from './paypal-commerce-request-sender';\nimport PayPalCommerceScriptLoader from './paypal-commerce-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceInitializationData,\n PayPalCreateOrderCardFieldsResponse,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {}\n\n /**\n *\n * PayPalSDK methods\n *\n */\n async loadPayPalSdk(\n methodId: string,\n providedCurrencyCode?: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const currencyCode = providedCurrencyCode || state.getCartOrThrow().currency.code;\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.paypalSdk = await this.paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n forceLoad,\n );\n\n return this.paypalSdk;\n }\n\n getPayPalSdkOrThrow(): PayPalSDK {\n if (!this.paypalSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalSdk;\n }\n\n /**\n *\n * Buy Now cart creation methods\n *\n */\n async createBuyNowCartOrThrow(\n buyNowInitializeOptions: PayPalBuyNowInitializeOptions,\n ): Promise {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(cartRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n /**\n *\n * Order methods\n *\n */\n async createOrder(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return orderId;\n }\n\n async createOrderCardFields(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId, setupToken } = await this.paypalCommerceRequestSender.createOrder(\n providerId,\n {\n cartId,\n ...requestBody,\n },\n );\n\n return { orderId, ...(setupToken ? { setupToken } : {}) };\n }\n\n async updateOrder(): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalCommerceRequestSender.updateOrder({\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n });\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n async getOrderStatus(methodId?: string, options?: RequestOptions): Promise {\n try {\n const { status } = await this.paypalCommerceRequestSender.getOrderStatus(\n methodId,\n options,\n );\n\n return status;\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n /**\n *\n * Payment submitting and tokenizing methods\n *\n */\n tokenizePayment(methodId: string, orderId?: string): void {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n action: 'set_external_checkout',\n provider: methodId,\n order_id: orderId,\n ...(cart.source === CartSource.BuyNow && { cart_id: cart.id }),\n });\n }\n\n async submitPayment(methodId: string, orderId: string, gatewayId?: string): Promise {\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n ...(gatewayId ? { gatewayId } : {}),\n });\n }\n\n /**\n *\n * Shipping options methods\n *\n */\n getShippingOptionOrThrow(selectedShippingOptionId?: string): ShippingOption {\n const state = this.paymentIntegrationService.getState();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n const availableShippingOptions = consignment.availableShippingOptions || [];\n\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n const selectedShippingOption = selectedShippingOptionId\n ? availableShippingOptions.find((option) => option.id === selectedShippingOptionId)\n : availableShippingOptions.find(\n (option) => option.id === consignment.selectedShippingOption?.id,\n );\n\n const shippingOptionToSelect =\n selectedShippingOption || recommendedShippingOption || availableShippingOptions[0];\n\n if (!shippingOptionToSelect) {\n throw new Error(\"Your order can't be shipped to this address\");\n }\n\n return shippingOptionToSelect;\n }\n\n /**\n *\n * Address transforming methods\n *\n */\n getAddress(address?: Partial): BillingAddressRequestBody {\n return {\n firstName: address?.firstName || '',\n lastName: address?.lastName || '',\n email: address?.email || '',\n phone: '',\n company: '',\n address1: address?.address1 || '',\n address2: address?.address2 || '',\n city: address?.city || '',\n countryCode: address?.countryCode || '',\n postalCode: address?.postalCode || '',\n stateOrProvince: '',\n stateOrProvinceCode: address?.stateOrProvinceCode || '',\n customFields: [],\n };\n }\n\n getBillingAddressFromOrderDetails({ payer }: PayPalOrderDetails): BillingAddressRequestBody {\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: payer.address.address_line_1,\n address2: payer.address.address_line_2,\n city: payer.address.admin_area_2,\n countryCode: payer.address.country_code,\n postalCode: payer.address.postal_code,\n stateOrProvinceCode: payer.address.admin_area_1,\n });\n }\n\n getShippingAddressFromOrderDetails(\n orderDetails: PayPalOrderDetails,\n ): BillingAddressRequestBody {\n const { payer, purchase_units } = orderDetails;\n const {\n address,\n name: { full_name },\n } = purchase_units[0].shipping;\n\n const [firstName, ...lastName] = full_name.split(' ');\n\n return this.getAddress({\n firstName,\n lastName: lastName.join(' '),\n email: payer.email_address,\n address1: address.address_line_1,\n address2: address.address_line_2,\n city: address.admin_area_2,\n countryCode: address.country_code,\n postalCode: address.postal_code,\n stateOrProvinceCode: address.admin_area_1,\n });\n }\n\n /**\n *\n * Buttons style methods\n *\n */\n getValidButtonStyle(style?: PayPalButtonStyleOptions): PayPalButtonStyleOptions {\n const { color, height, label, shape } = style || {};\n\n const validStyles = {\n color: color && StyleButtonColor[color] ? color : undefined,\n height: this.getValidHeight(height),\n label: label && StyleButtonLabel[label] ? label : undefined,\n shape: shape && StyleButtonShape[shape] ? shape : undefined,\n };\n\n return omitBy(validStyles, isNil);\n }\n\n getValidHeight(height?: number): number {\n const defaultHeight = 40;\n const minHeight = 25;\n const maxHeight = 55;\n\n if (!height || typeof height !== 'number') {\n return defaultHeight;\n }\n\n if (height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n }\n\n /**\n *\n * Utils methods\n *\n */\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n // For now this is a temporary solution, further removeElement method will be removed\n element.style.display = 'none';\n }\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCreateOrderRequestBody,\n PayPalOrderData,\n PayPalOrderStatusData,\n PayPalUpdateOrderRequestBody,\n PayPalUpdateOrderResponse,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async createOrder(\n providerId: string,\n requestBody: Partial,\n ): Promise {\n const url = `/api/storefront/payment/${providerId}`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.post(url, { headers, body });\n\n return res.body;\n }\n\n async updateOrder(\n requestBody: PayPalUpdateOrderRequestBody,\n ): Promise {\n const url = `/api/storefront/initialization/paypalcommerce`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.put(url, { headers, body });\n\n return res.body;\n }\n\n async getOrderStatus(\n methodId = 'paypalcommerce',\n options?: RequestOptions,\n ): Promise {\n const url = `/api/storefront/initialization/${methodId}`;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.get(url, {\n headers,\n ...options,\n });\n\n return res.body;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n ComponentsScriptType,\n FundingType,\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n forceLoad?: boolean,\n ): Promise {\n const paypalSdkScriptConfig = this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.loadPayPalSDK(paypalSdkScriptConfig, forceLoad);\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n forceLoad = false,\n ): Promise {\n if (!this.window.paypal || forceLoad) {\n const options = this.transformConfig(\n paypalSdkScriptConfig.options,\n );\n const attributes = this.transformConfig(\n paypalSdkScriptConfig.attributes,\n );\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(options).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes });\n }\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n isGooglePayEnabled,\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n const googlePayComponent: ComponentsScriptType = isGooglePayEnabled ? ['googlepay'] : [];\n const cardFieldsComponent: ComponentsScriptType = initializesOnCheckoutPage\n ? ['card-fields']\n : [];\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: [\n 'buttons',\n 'hosted-fields',\n 'payment-fields',\n 'legal',\n ...googlePayComponent,\n ...cardFieldsComponent,\n ],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n },\n };\n }\n\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceIntegrationService,\n PayPalCommerceRequestSender,\n PayPalCommerceScriptLoader,\n} from './index';\n\nconst createPayPalCommerceIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n new PayPalCommerceScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createPayPalCommerceIntegrationService;\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCustomerInitializeOptions,\n ): Promise {\n const { paypalcommerce, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce.container\" argument is not provided.',\n );\n }\n\n if (paypalcommerce.onClick && typeof paypalcommerce.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommerce.onClick\" argument is not a function.',\n );\n }\n\n this.onError = paypalcommerce.onError || noop;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommerceCustomerInitializeOptions,\n ): void {\n const { container, onClick, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: unknown) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCustomerInitializeOptions, {\n WithPayPalCommerceCreditCustomerInitializeOptions,\n} from './paypal-commerce-credit-customer-initialize-options';\n\nexport default class PayPalCommerceCreditCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCreditCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit.container\" argument is not provided.',\n );\n }\n\n if (paypalcommercecredit.onClick && typeof paypalcommercecredit.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercecredit.onClick\" argument is not a function.',\n );\n }\n\n this.onError = paypalcommercecredit.onError || noop;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercecredit);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalCommerceCredit: PayPalCommerceCreditCustomerInitializeOptions,\n ): void {\n const { container, onComplete, onClick } = paypalCommerceCredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled, paymentButtonStyles } =\n paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: unknown) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCustomerStrategy from './paypal-commerce-credit-customer-strategy';\n\nconst createPayPalCommerceCreditCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCreditCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditCustomerStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n DefaultCheckoutButtonHeight,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoCustomerInitializeOptions, {\n WithPayPalCommerceVenmoCustomerInitializeOptions,\n} from './paypal-commerce-venmo-customer-initialize-options';\n\nexport default class PayPalCommerceVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceVenmoCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo.container\" argument is not provided.',\n );\n }\n\n if (paypalcommercevenmo.onClick && typeof paypalcommercevenmo.onClick !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercevenmo.onClick\" argument is not a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoCustomerInitializeOptions,\n ): void {\n const { container, onClick } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutTopButtonStyles } = paymentButtonStyles || {};\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n ...checkoutTopButtonStyles,\n height: DefaultCheckoutButtonHeight,\n }),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n ...(onClick && { onClick: () => onClick() }),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoCustomerStrategy from './paypal-commerce-venmo-customer-strategy';\n\nconst createPayPalCommerceVenmoCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoCustomerStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalFastlaneSdk,\n PayPalMessagesSdk,\n PayPalSdkConfig,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceSdk {\n private window: PayPalCommerceHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalFastlaneSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n ): Promise {\n if (!this.window.paypalFastlaneSdk) {\n const config = this.getPayPalFastlaneSdkConfiguration(\n paymentMethod,\n currencyCode,\n sessionId,\n );\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.paypalFastlaneSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalFastlaneSdk;\n }\n\n async getPayPalApmsSdk(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ) {\n if (!this.window.paypalApms) {\n const config = this.getPayPalApmSdkConfiguration(paymentMethod, currencyCode);\n\n await this.loadPayPalSdk(config);\n\n if (!this.window.paypalApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalApms;\n }\n\n async getPayPalMessages(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): Promise {\n if (!this.window.paypalMessages) {\n const paypalSdkMessagesConfig = this.getPayPalSdkMessagesConfiguration(\n paymentMethod,\n currencyCode,\n );\n\n await this.loadPayPalSdk(paypalSdkMessagesConfig);\n\n if (!this.window.paypalMessages) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.window.paypalMessages;\n }\n\n /**\n *\n * loadPayPalSdk is a paypal sdk script loader\n * which loads paypal sdk based on provided configuration\n *\n */\n private async loadPayPalSdk({ options, attributes }: PayPalSdkConfig): Promise {\n const scriptOptions = this.transformConfig(options);\n const scriptAttributes = this.transformConfig(attributes);\n\n const paypalSdkUrl = 'https://www.paypal.com/sdk/js';\n const scriptQuery = new URLSearchParams(scriptOptions).toString();\n const scriptSrc = `${paypalSdkUrl}?${scriptQuery}`;\n\n await this.scriptLoader.loadScript(scriptSrc, {\n async: true,\n attributes: scriptAttributes,\n });\n }\n\n /**\n *\n * Configurations section\n *\n */\n private getPayPalFastlaneSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n sessionId: string,\n ): PayPalSdkConfig {\n const { clientToken, initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n attributionId,\n connectClientToken, // TODO: remove when PPCP Fastlane A/B testing will be finished\n } = initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n commit: true,\n components: ['fastlane'],\n currency: currencyCode,\n intent,\n },\n attributes: {\n 'data-client-metadata-id': sessionId.replace(/-/g, ''),\n 'data-namespace': 'paypalFastlaneSdk',\n 'data-partner-attribution-id': attributionId,\n 'data-user-id-token': connectClientToken || clientToken,\n },\n };\n }\n\n private getPayPalApmSdkConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): PayPalSdkConfig {\n const { initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n } = initializationData;\n\n const enableAPMsFunding = enabledAlternativePaymentMethods;\n const disableAPMsFunding = availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n );\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n 'enable-funding': enableAPMsFunding.length > 0 ? enableAPMsFunding : undefined,\n 'disable-funding': disableAPMsFunding.length > 0 ? disableAPMsFunding : undefined,\n commit: true,\n components: ['buttons', 'payment-fields'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-partner-attribution-id': attributionId,\n 'data-namespace': 'paypalApms',\n },\n };\n }\n\n private getPayPalSdkMessagesConfiguration(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n ): PayPalSdkConfig {\n const { initializationData } = paymentMethod;\n\n if (!initializationData || !initializationData.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { clientId, merchantId, attributionId, isDeveloperModeApplicable, buyerCountry } =\n initializationData;\n\n return {\n options: {\n 'client-id': clientId,\n 'merchant-id': merchantId,\n components: ['messages'],\n currency: currencyCode,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n },\n attributes: {\n 'data-namespace': 'paypalMessages',\n 'data-partner-attribution-id': attributionId,\n },\n };\n }\n\n /**\n *\n * Utils methods\n *\n */\n private transformConfig>(config: T): Record {\n let transformedConfig = {};\n\n const keys = Object.keys(config) as Array;\n\n keys.forEach((key) => {\n const value = config[key];\n\n if (\n value === undefined ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return;\n }\n\n transformedConfig = {\n ...transformedConfig,\n [key]: Array.isArray(value) ? value.join(',') : value,\n };\n });\n\n return transformedConfig;\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport PayPalCommerceSdk from './paypal-commerce-sdk';\n\nexport default function createPayPalCommerceSdk(): PayPalCommerceSdk {\n return new PayPalCommerceSdk(createScriptLoader());\n}\n","import { CardInstrument, CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n fastlaneStyles?: FastlaneStylesSettings;\n connectClientToken?: string; // TODO: remove when PPCP Fastlane A/B test will be finished\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isAcceleratedCheckoutEnabled?: boolean; // PayPal Fastlane related\n isFastlaneShippingOptionAutoSelectEnabled?: boolean; // PayPal Fastlane related\n isFastlaneStylingEnabled?: boolean;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCommerceAnalyticsV2Enabled?: boolean; // PayPal Fastlane related\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n isGooglePayEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n shouldRunAcceleratedCheckout?: boolean; // TODO: remove when PPCP Fastlane A/B test will be finished\n paymentButtonStyles?: Record;\n paypalBNPLConfiguration?: PayPalBNPLConfigurationItem[];\n}\n\n/**\n *\n * PayPalCommerceHostWindow contains different\n * PayPal Sdk instances for different purposes\n *\n */\nexport interface PayPalCommerceHostWindow extends Window {\n paypalFastlane?: PayPalFastlane;\n paypalFastlaneSdk?: PayPalFastlaneSdk;\n paypalMessages?: PayPalMessagesSdk;\n paypalApms?: PayPalApmSdk;\n}\n\n/**\n *\n * PayPal SDK config\n *\n */\nexport interface PayPalSdkConfig {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'enable-funding'?: EnableFundingType;\n 'disable-funding'?: FundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: PayPalSdkComponents;\n };\n attributes: {\n 'data-client-metadata-id'?: string;\n 'data-partner-attribution-id'?: string;\n 'data-user-id-token'?: string;\n 'data-namespace'?: string;\n 'data-client-token'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type PayPalSdkComponents = Array<'fastlane' | 'messages' | 'buttons' | 'payment-fields'>;\n\n/**\n *\n * PayPal Sdk instances\n *\n */\nexport interface PayPalFastlaneSdk {\n Fastlane(options?: PayPalFastlaneOptions): Promise;\n}\n\nexport interface PayPalMessagesSdk {\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PayPalApmSdk {\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: PayPalButtonApproveCallbackPayload,\n actions: PayPalButtonApproveCallbackActions,\n ): Promise | void;\n onInit?(\n data: PayPalButtonInitCallbackPayload,\n actions: PayPalButtonInitCallbackActions,\n ): Promise;\n onClick?(\n data: PayPalButtonClickCallbackPayload,\n actions: PayPalButtonClickCallbackActions,\n ): Promise | void;\n onError?(error: Error): void;\n onCancel?(): void;\n}\n\nexport interface PayPalButtonClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface PayPalButtonClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface PayPalButtonInitCallbackPayload {\n correlationID: string;\n}\n\nexport interface PayPalButtonInitCallbackActions {\n disable(): void;\n enable(): void;\n}\n\nexport interface PayPalButtonApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface PayPalButtonApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayLater Messages related types\n * doc: https://developer.paypal.com/docs/checkout/pay-later/us/integrate/reference\n */\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagesStyleOptions {\n color?: string; // 'blue' | 'black' | 'white' | 'white-no-border' | 'gray' | 'monochrome' | 'grayscale'\n layout?: string; // 'text' | 'flex'\n logo?: {\n type?: string; // 'primary' | 'alternative' | 'inline' | 'none'\n position?: string; // 'left' | 'right' | 'top'\n };\n ratio?: string; // '1x1' | '1x4' | '8x1' | '20x1'\n text?: {\n align?: string; // 'left' | 'right' | 'center'\n color?: string; // 'black' | 'white' | 'monochrome' | 'grayscale'\n size?: number; // from 10 to 16\n };\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface PayPalBNPLConfigurationItem {\n id: string;\n name: string;\n status: boolean;\n styles: Record;\n}\n\n/**\n *\n * PayPal Fastlane related types\n *\n */\nexport interface PayPalFastlane {\n identity: PayPalFastlaneIdentity;\n events: PayPalFastlaneEvents;\n profile: PayPalFastlaneProfile;\n FastlaneCardComponent(\n options: PayPalFastlaneCardComponentOptions,\n ): Promise;\n}\n\nexport interface PayPalFastlaneOptions {\n styles?: PayPalFastlaneStylesOption;\n}\n\nexport interface PayPalFastlaneIdentity {\n lookupCustomerByEmail(email: string): Promise;\n triggerAuthenticationFlow(\n customerContextId: string,\n ): Promise;\n}\n\nexport interface PayPalFastlaneLookupCustomerByEmailResult {\n customerContextId?: string;\n}\n\nexport interface PayPalFastlaneAuthenticationResult {\n authenticationState?: PayPalFastlaneAuthenticationState;\n profileData?: PayPalFastlaneProfileData;\n}\n\nexport enum PayPalFastlaneAuthenticationState {\n SUCCEEDED = 'succeeded',\n FAILED = 'failed',\n CANCELED = 'cancelled',\n UNRECOGNIZED = 'unrecognized',\n}\n\nexport interface PayPalFastlaneProfileData {\n name: PayPalFastlaneProfileName;\n shippingAddress: PayPalFastlaneShippingAddress;\n card: PayPalFastlaneProfileCard;\n}\n\nexport interface PayPalFastlaneProfileName {\n fullName: string;\n firstName?: string;\n lastName?: string;\n}\n\nexport interface PayPalFastlaneProfilePhone {\n countryCode: string;\n nationalNumber: string;\n}\n\nexport interface PayPalFastlaneShippingAddress {\n name: PayPalFastlaneProfileName;\n phoneNumber: PayPalFastlaneProfilePhone;\n address: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneProfileCard {\n id: string; // nonce / token\n paymentSource: PayPalFastlanePaymentSource;\n}\n\nexport interface PayPalFastlanePaymentSource {\n card: PayPalFastlaneCardSource;\n}\n\nexport interface PayPalFastlaneCardSource {\n brand: string;\n expiry: string; // \"YYYY-MM\"\n lastDigits: string; // \"1111\"\n name: string;\n billingAddress: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneAddress {\n company?: string;\n addressLine1: string;\n addressLine2?: string;\n adminArea1: string; // State\n adminArea2: string; // City\n postalCode: string;\n countryCode?: string;\n}\n\nexport interface PayPalFastlaneProfileToBcCustomerDataMappingResult {\n authenticationState: PayPalFastlaneAuthenticationState;\n addresses: CustomerAddress[];\n billingAddress?: CustomerAddress;\n shippingAddress?: CustomerAddress;\n instruments: CardInstrument[];\n}\n\nexport interface PayPalFastlaneStylesOption {\n root?: {\n backgroundColorPrimary?: string;\n errorColor?: string;\n fontFamily?: string;\n fontSizeBase?: string;\n padding?: string;\n primaryColor?: string;\n };\n input?: {\n borderRadius?: string;\n borderColor?: string;\n focusBorderColor?: string;\n backgroundColor?: string;\n borderWidth?: string;\n textColorBase?: string;\n };\n toggle?: {\n colorPrimary?: string;\n colorSecondary?: string;\n };\n text?: {\n body?: {\n color?: string;\n fontSize?: string;\n };\n caption?: {\n color?: string;\n fontSize?: string;\n };\n };\n branding?: string; // 'light' | 'dark'\n}\n\nexport interface PayPalFastlaneProfile {\n showCardSelector(): Promise;\n showShippingAddressSelector(): Promise;\n}\n\nexport interface PayPalFastlaneShippingAddressSelectorResponse {\n selectionChanged: boolean;\n selectedAddress: PayPalFastlaneShippingAddress;\n}\n\nexport interface PayPalFastlaneCardSelectorResponse {\n selectionChanged: boolean;\n selectedCard: PayPalFastlaneProfileCard;\n}\n\nexport interface PayPalFastlaneCardComponentMethods {\n getPaymentToken(\n options: PayPalFastlaneGetPaymentTokenOptions,\n ): Promise;\n render(element: string): void;\n}\n\nexport interface PayPalFastlaneGetPaymentTokenOptions {\n name?: PayPalFastlaneProfileName;\n billingAddress?: PayPalFastlaneAddress;\n}\n\nexport interface PayPalFastlaneCardComponentOptions {\n fields?: PayPalFastlaneCardComponentFields;\n}\n\nexport interface PayPalFastlaneCardComponentFields {\n cardholderName?: {\n enabled?: boolean;\n prefill?: string;\n };\n phoneNumber?: {\n placeholder?: string;\n prefill?: string;\n };\n}\n\nexport interface PayPalFastlaneEvents {\n apmSelected: (options: PayPalFastlaneApmSelectedEventOptions) => void;\n emailSubmitted: (options: PayPalFastlaneEmailEnteredEventOptions) => void;\n orderPlaced: (options: PayPalFastlaneOrderPlacedEventOptions) => void;\n}\n\nexport interface PayPalFastlaneEventCommonOptions {\n context_type: 'cs_id';\n context_id: string; // checkout session id\n page_type: 'checkout_page';\n page_name: string; // title of the checkout initiation page\n partner_name: 'bigc';\n user_type: 'store_member' | 'store_guest'; // type of the user on the merchant site\n store_id: string;\n merchant_name: string;\n experiment: string; // stringify JSON object \"[{ treatment_group: 'test' | 'control' }]\"\n}\n\nexport interface PayPalFastlaneApmSelectedEventOptions extends PayPalFastlaneEventCommonOptions {\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page\n apm_selected: string; // alternate payment method selected / methodId\n apm_location: 'pre-email section' | 'payment section'; // placement of APM, whether it be above the email entry or in the radio buttons\n}\n\nexport interface PayPalFastlaneEmailEnteredEventOptions extends PayPalFastlaneEventCommonOptions {\n user_email_saved: boolean; // shows whether checkout was loaded with or without a saved email\n apm_shown: '0' | '1'; // alternate payment shown on the checkout page\n apm_list: string; // list of alternate payment shown on checkout page 'applepay,googlepay,paypal'\n}\n\nexport interface PayPalFastlaneOrderPlacedEventOptions extends PayPalFastlaneEventCommonOptions {\n selected_payment_method: string;\n currency_code: string;\n}\n\nexport interface PayPalFastlanePaymentFormattedPayload {\n paypal_connect_token?: {\n order_id?: string;\n token: string;\n };\n paypal_fastlane_token?: {\n order_id?: string;\n token: string;\n };\n}\n\nexport interface FastlaneStylesSettings {\n fastlaneRootSettingsBackgroundColor?: string;\n fastlaneRootSettingsErrorColor?: string;\n fastlaneRootSettingsFontFamily?: string;\n fastlaneRootSettingsPadding?: string;\n fastlaneRootSettingsPrimaryColor?: string;\n fastlaneRootSettingsFontSize?: string;\n fastlaneInputSettingsBackgroundColor?: string;\n fastlaneInputSettingsBorderRadius?: string;\n fastlaneInputSettingsBorderWidth?: string;\n fastlaneInputSettingsTextColorBase?: string;\n fastlaneInputSettingsBorderColor?: string;\n fastlaneInputSettingsFocusBorderBase?: string;\n fastlaneToggleSettingsColorPrimary?: string;\n fastlaneToggleSettingsColorSecondary?: string;\n fastlaneTextBodySettingsColor?: string;\n fastlaneTextBodySettingsFontSize?: string;\n fastlaneTextCaptionSettingsFontSize?: string;\n fastlaneTextCaptionSettingsColor?: string;\n fastlaneBrandingSettings?: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n Address,\n CardInstrument,\n CustomerAddress,\n PaymentMethodClientUnavailableError,\n UntrustedShippingCardVerificationType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport {\n PayPalCommerceHostWindow,\n PayPalFastlane,\n PayPalFastlaneAddress,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneLookupCustomerByEmailResult,\n PayPalFastlaneProfileCard,\n PayPalFastlaneProfileName,\n PayPalFastlaneProfilePhone,\n PayPalFastlaneProfileToBcCustomerDataMappingResult,\n PayPalFastlaneSdk,\n PayPalFastlaneStylesOption,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceFastlaneUtils {\n private window: PayPalCommerceHostWindow;\n\n constructor(private browserStorage: BrowserStorage) {\n this.window = window;\n }\n\n async initializePayPalFastlane(\n paypalFastlaneSdk: PayPalFastlaneSdk,\n isTestModeEnabled: boolean,\n styles?: PayPalFastlaneStylesOption,\n ): Promise {\n if (isTestModeEnabled) {\n window.localStorage.setItem('fastlaneEnv', 'sandbox');\n window.localStorage.setItem('axoEnv', 'sandbox'); // TODO: remove if this key does not use on PayPal side\n }\n\n if (!this.window.paypalFastlane) {\n const defaultStyles = {\n root: {\n backgroundColorPrimary: 'transparent',\n },\n };\n\n this.window.paypalFastlane = await paypalFastlaneSdk.Fastlane({\n styles: styles || defaultStyles,\n });\n }\n\n return this.window.paypalFastlane;\n }\n\n getPayPalFastlaneOrThrow(): PayPalFastlane {\n if (!this.window.paypalFastlane) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypalFastlane;\n }\n\n /**\n *\n * Detects the customer to PayPal Fastlane relation and\n * returns customerContextId to use it for authentication\n *\n */\n async lookupCustomerOrThrow(email: string): Promise {\n const paypalFastlane = this.getPayPalFastlaneOrThrow();\n\n return paypalFastlane.identity.lookupCustomerByEmail(email);\n }\n\n /**\n *\n * Triggers authentication flow (shows OTP popup) if the customer recognised as PayPal Fastlane user\n * and returns PayPal Fastlane Profile data to use it in BC checkout\n *\n */\n async triggerAuthenticationFlowOrThrow(\n customerContextId?: string,\n ): Promise {\n if (!customerContextId) {\n return {};\n }\n\n const paypalFastlane = this.getPayPalFastlaneOrThrow();\n\n return paypalFastlane.identity.triggerAuthenticationFlow(customerContextId);\n }\n\n /**\n *\n * 'updateStorageSessionId' method is used to:\n * - set session id after user was authenticated (or unrecognised) to trigger authentication after page refresh\n * - remove sessionId from browser storage if the customer canceled PayPal Fastlane Authentication\n *\n * Flow info:\n * If user unrecognised then the lookup method will be working but the OTP will not be shown\n * If user recognised and not canceled then the lookup method will be working and the OTP will be shown only if needed\n * If user cancels the OPT then OTP will not be triggered after page refresh\n *\n */\n updateStorageSessionId(shouldBeRemoved: boolean, sessionId?: string): void {\n if (shouldBeRemoved) {\n // TODO: Should be rewritten to cookies implementation\n this.browserStorage.removeItem('sessionId');\n } else {\n // TODO: Should be rewritten to cookies implementation\n this.browserStorage.setItem('sessionId', sessionId);\n }\n }\n\n getStorageSessionId(): string {\n // TODO: Should be rewritten to cookies implementation\n return this.browserStorage.getItem('sessionId') || '';\n }\n\n /**\n *\n * 'mapPayPalFastlaneProfileToBcCustomerData' method is responsible for:\n * - mapping PayPal Fastlane Profile data to BC data shape\n * - returning mapped data to use for updating PaymentProviderCustomer state and\n * update shipping and billing addresses\n *\n */\n mapPayPalFastlaneProfileToBcCustomerData(\n methodId: string,\n authenticationResult: PayPalFastlaneAuthenticationResult,\n ): PayPalFastlaneProfileToBcCustomerDataMappingResult {\n const { authenticationState, profileData } = authenticationResult;\n\n const paypalBillingAddress = profileData?.card?.paymentSource?.card?.billingAddress;\n const paypalShippingAddress = profileData?.shippingAddress;\n const paypalProfileName = profileData?.name;\n const paypalInstrument = profileData?.card;\n\n const shippingAddress = paypalShippingAddress\n ? this.mapPayPalToBcAddress(\n paypalShippingAddress.address,\n paypalShippingAddress.name,\n paypalShippingAddress.phoneNumber,\n )\n : undefined;\n const billingAddress =\n paypalBillingAddress && paypalProfileName\n ? this.mapPayPalToBcAddress(\n paypalBillingAddress,\n paypalProfileName,\n paypalShippingAddress?.phoneNumber,\n )\n : undefined;\n const instruments = paypalInstrument\n ? this.mapPayPalToBcInstrument(methodId, paypalInstrument)\n : [];\n\n const addresses = this.filterAddresses([shippingAddress, billingAddress]);\n\n return {\n authenticationState:\n authenticationState || PayPalFastlaneAuthenticationState.UNRECOGNIZED,\n addresses,\n billingAddress,\n shippingAddress,\n instruments,\n };\n }\n\n mapPayPalToBcInstrument(\n methodId: string,\n instrument: PayPalFastlaneProfileCard,\n ): CardInstrument[] {\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return [\n {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.PAN,\n type: 'card',\n },\n ];\n }\n\n mapBcToPayPalAddress(address?: Address): PayPalFastlaneAddress {\n return {\n company: address?.company || '',\n addressLine1: address?.address1 || '',\n addressLine2: address?.address2 || '',\n adminArea1: address?.stateOrProvinceCode || address?.stateOrProvince || '',\n adminArea2: address?.city || '',\n postalCode: address?.postalCode || '',\n countryCode: address?.countryCode || '',\n };\n }\n\n mapPayPalToBcAddress(\n address: PayPalFastlaneAddress,\n profileName: PayPalFastlaneProfileName,\n phone?: PayPalFastlaneProfilePhone,\n customFields?: CustomerAddress['customFields'],\n ): CustomerAddress {\n const [firstName, lastName] = profileName.fullName.split(' ');\n\n const phoneData = {\n nationalNumber: phone?.nationalNumber || '',\n countryCode: phone?.countryCode || '',\n };\n\n return {\n id: Date.now(),\n type: 'paypal-address',\n firstName: profileName.firstName || firstName || '',\n lastName: profileName.lastName || lastName || '',\n company: address.company || '',\n address1: address.addressLine1,\n address2: address.addressLine2 || '',\n city: address.adminArea2,\n stateOrProvince: address.adminArea1,\n stateOrProvinceCode: address.adminArea1,\n country: address.countryCode || '', // TODO: update country with valid naming\n countryCode: address.countryCode || '',\n postalCode: address.postalCode,\n phone: phoneData.countryCode + phoneData.nationalNumber,\n customFields: customFields || [],\n };\n }\n\n /**\n *\n * This method is responsible for filtering PayPal Fastlane addresses if they are the same\n * and returns an array of addresses to use them for shipping and/or billing address selections\n * so the customer will be able to use addresses from PayPal Fastlane in checkout flow\n *\n */\n filterAddresses(addresses: Array): CustomerAddress[] {\n return addresses.reduce(\n (customerAddresses: CustomerAddress[], currentAddress: CustomerAddress | undefined) => {\n if (!currentAddress) {\n return customerAddresses;\n }\n\n const sameAddressInTheArray = customerAddresses.some((customerAddress) =>\n this.isEqualAddresses(customerAddress, currentAddress),\n );\n\n return sameAddressInTheArray\n ? customerAddresses\n : [...customerAddresses, currentAddress];\n },\n [],\n );\n }\n\n private isEqualAddresses(\n firstAddress: CustomerAddress,\n secondAddress: CustomerAddress,\n ): boolean {\n return isEqual(this.normalizeAddress(firstAddress), this.normalizeAddress(secondAddress));\n }\n\n private normalizeAddress(address: CustomerAddress) {\n return omit(address, ['id', 'phone']);\n }\n}\n","import { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport PayPalCommerceFastlaneUtils from './paypal-commerce-fastlane-utils';\n\nexport default function createPayPalCommerceFastlaneUtils(): PayPalCommerceFastlaneUtils {\n return new PayPalCommerceFastlaneUtils(new BrowserStorage('paypalFastlane'));\n}\n","import { omitBy } from 'lodash';\n\nimport { FastlaneStylesSettings, PayPalFastlaneStylesOption } from '../index';\n\nfunction isInvalidStyleOption(styleOption: unknown) {\n return typeof styleOption !== 'string';\n}\n\nexport default function getFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: PayPalFastlaneStylesOption,\n) {\n if (!uiStyles && !styleSettings) {\n return undefined;\n }\n\n return cleanUpFastlaneStyles(mergeFastlaneStyles(styleSettings, uiStyles));\n}\n\nfunction mergeFastlaneStyles(\n styleSettings?: FastlaneStylesSettings,\n uiStyles?: PayPalFastlaneStylesOption,\n): PayPalFastlaneStylesOption {\n return {\n root: {\n backgroundColorPrimary:\n styleSettings?.fastlaneRootSettingsBackgroundColor ||\n uiStyles?.root?.backgroundColorPrimary,\n errorColor: styleSettings?.fastlaneRootSettingsErrorColor || uiStyles?.root?.errorColor,\n fontFamily: styleSettings?.fastlaneRootSettingsFontFamily || uiStyles?.root?.fontFamily,\n fontSizeBase:\n styleSettings?.fastlaneRootSettingsFontSize || uiStyles?.root?.fontSizeBase,\n padding: styleSettings?.fastlaneRootSettingsPadding || uiStyles?.root?.padding,\n primaryColor:\n styleSettings?.fastlaneRootSettingsPrimaryColor || uiStyles?.root?.primaryColor,\n },\n input: {\n borderRadius:\n styleSettings?.fastlaneInputSettingsBorderRadius || uiStyles?.input?.borderRadius,\n borderColor:\n styleSettings?.fastlaneInputSettingsBorderColor || uiStyles?.input?.borderColor,\n focusBorderColor:\n styleSettings?.fastlaneInputSettingsFocusBorderBase ||\n uiStyles?.input?.focusBorderColor,\n backgroundColor:\n styleSettings?.fastlaneInputSettingsBackgroundColor ||\n uiStyles?.input?.backgroundColor,\n borderWidth:\n styleSettings?.fastlaneInputSettingsBorderWidth || uiStyles?.input?.borderWidth,\n textColorBase:\n styleSettings?.fastlaneInputSettingsTextColorBase || uiStyles?.input?.textColorBase,\n },\n toggle: {\n colorPrimary:\n styleSettings?.fastlaneToggleSettingsColorPrimary || uiStyles?.toggle?.colorPrimary,\n colorSecondary:\n styleSettings?.fastlaneToggleSettingsColorSecondary ||\n uiStyles?.toggle?.colorSecondary,\n },\n text: {\n body: {\n color: styleSettings?.fastlaneTextBodySettingsColor || uiStyles?.text?.body?.color,\n fontSize:\n styleSettings?.fastlaneTextBodySettingsFontSize ||\n uiStyles?.text?.body?.fontSize,\n },\n caption: {\n color:\n styleSettings?.fastlaneTextCaptionSettingsColor ||\n uiStyles?.text?.caption?.color,\n fontSize:\n styleSettings?.fastlaneTextCaptionSettingsFontSize ||\n uiStyles?.text?.caption?.fontSize,\n },\n },\n branding: styleSettings?.fastlaneBrandingSettings || uiStyles?.branding,\n };\n}\n\nfunction cleanUpFastlaneStyles(styles: PayPalFastlaneStylesOption) {\n const fastlaneStyles: PayPalFastlaneStylesOption = {};\n\n const root = omitBy(styles.root, isInvalidStyleOption);\n const input = omitBy(styles.input, isInvalidStyleOption);\n const toggle = omitBy(styles.toggle, isInvalidStyleOption);\n const textBody = omitBy(styles.text?.body, isInvalidStyleOption);\n const textCaption = omitBy(styles.text?.caption, isInvalidStyleOption);\n const branding = styles.branding;\n\n if (Object.keys(root).length) {\n fastlaneStyles.root = root;\n }\n\n if (Object.keys(input).length) {\n fastlaneStyles.input = input;\n }\n\n if (Object.keys(toggle).length) {\n fastlaneStyles.toggle = toggle;\n }\n\n if (Object.keys(textBody).length) {\n fastlaneStyles.text = {};\n fastlaneStyles.text.body = textBody;\n }\n\n if (Object.keys(textCaption).length) {\n fastlaneStyles.text = {\n ...fastlaneStyles.text,\n };\n fastlaneStyles.text.caption = textCaption;\n }\n\n if (branding) {\n fastlaneStyles.branding = branding;\n }\n\n return fastlaneStyles;\n}\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationResult,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceFastlaneCustomerInitializeOptions, {\n WithPayPalCommerceFastlaneCustomerInitializeOptions,\n} from './paypal-commerce-fastlane-customer-initialize-options';\n\nexport default class PayPalCommerceFastlaneCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceFastlaneCustomerInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n try {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const isTestModeEnabled = !!paymentMethod.initializationData?.isDeveloperModeApplicable;\n\n const paypalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n this.getFastlaneStyles(methodId, paypalcommercefastlane),\n );\n } catch (_) {\n // TODO: add logger to be able to debug issues if there any\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n\n return Promise.resolve();\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const { checkoutPaymentMethodExecuted, continueWithCheckoutCallback, methodId } =\n options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomerOrThrow();\n\n if (customer.isGuest) {\n if (\n checkoutPaymentMethodExecuted &&\n typeof checkoutPaymentMethodExecuted === 'function'\n ) {\n checkoutPaymentMethodExecuted();\n }\n\n try {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n } catch (_) {\n // TODO: add logger to be able to debug issues if there any\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n }\n\n continueWithCheckoutCallback();\n }\n\n /**\n *\n * Authentication flow methods\n *\n */\n private async runPayPalAuthenticationFlowOrThrow(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const customerEmail = customer?.email || billingAddress?.email || '';\n\n const { customerContextId } = await this.paypalCommerceFastlaneUtils.lookupCustomerOrThrow(\n customerEmail,\n );\n\n const authenticationResult =\n await this.paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n await this.updateCustomerDataState(methodId, authenticationResult);\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cartId,\n );\n }\n\n private async updateCustomerDataState(\n methodId: string,\n authenticationResult: PayPalFastlaneAuthenticationResult,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n\n const { authenticationState, addresses, billingAddress, shippingAddress, instruments } =\n this.paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n if (billingAddress) {\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n const updatedState = await this.paymentIntegrationService.updateShippingAddress(\n shippingAddress,\n );\n\n const paymentMethod =\n updatedState.getPaymentMethodOrThrow(methodId);\n const { isFastlaneShippingOptionAutoSelectEnabled } =\n paymentMethod.initializationData || {};\n const consignments = updatedState.getConsignments() || [];\n const availableShippingOptions = consignments[0]?.availableShippingOptions || [];\n const firstShippingOption = availableShippingOptions[0];\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n if (\n (recommendedShippingOption || firstShippingOption) &&\n isFastlaneShippingOptionAutoSelectEnabled\n ) {\n const shippingOptionId = recommendedShippingOption?.id || firstShippingOption.id;\n\n await this.paymentIntegrationService.selectShippingOption(shippingOptionId);\n }\n }\n }\n\n /**\n *\n * Fastlane styling methods\n *\n */\n private getFastlaneStyles(\n methodId: string,\n paypalcommercefastlane: PayPalCommerceFastlaneCustomerInitializeOptions | undefined,\n ): PayPalFastlaneStylesOption | undefined {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n const { fastlaneStyles, isFastlaneStylingEnabled } = paymentMethod.initializationData || {};\n\n return getFastlaneStyles(\n isFastlaneStylingEnabled ? fastlaneStyles : {},\n paypalcommercefastlane?.styles,\n );\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceFastlaneCustomerStrategy from './paypal-commerce-fastlane-customer-strategy';\n\nconst createPayPalCommerceFastlaneCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceFastlaneCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceFastlaneCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPayPalCommerceFastlaneCustomerStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // this method id will be provided for users from test group\n { id: 'paypalcommercecreditcards' }, // this method id will be provided for users from control group\n]);\n","import {\n PaymentProviderCustomer,\n StripeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isStripeAcceleratedCheckoutCustomer(\n customer: PaymentProviderCustomer,\n): customer is StripeAcceleratedCheckoutCustomer {\n return 'stripeLinkAuthenticationState' in customer;\n}\n","import { PaymentMethod } from '../stripev3/stripev3';\n\nimport { StripeUPEPaymentMethod } from './stripe-upe';\n\nexport function isStripeUPEPaymentMethodLike(\n paymentMethod: PaymentMethod,\n): paymentMethod is StripeUPEPaymentMethod {\n return (\n typeof paymentMethod === 'object' &&\n paymentMethod !== null &&\n 'initializationData' in paymentMethod &&\n (paymentMethod as StripeUPEPaymentMethod).initializationData !== undefined &&\n (paymentMethod as StripeUPEPaymentMethod).initializationData !== null &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData === 'object' &&\n 'stripePublishableKey' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n 'stripeConnectedAccount' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n 'shopperLanguage' in (paymentMethod as StripeUPEPaymentMethod).initializationData &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData.stripePublishableKey !==\n 'undefined' &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData\n .stripeConnectedAccount !== 'undefined' &&\n typeof (paymentMethod as StripeUPEPaymentMethod).initializationData.shopperLanguage !==\n 'undefined'\n );\n}\n","import {\n CustomFont,\n PaymentIntent,\n PaymentMethod,\n StripeConfigurationOptions,\n} from '../stripev3/stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3/stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n\n /**\n * Updates the options the Payment Element was initialized with. Updates are merged into the existing configuration.\n * https://docs.stripe.com/js/elements_object/update_payment_element\n */\n update(options?: StripeElementsCreateOptions): void;\n\n /**\n * This method collapses the Payment Element into a row of payment method tabs.\n * https://docs.stripe.com/js/elements_object/collapse_payment_element\n */\n collapse(): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: Address;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport interface StripePaymentEvent extends StripeEvent {\n value: {\n type: StripePaymentMethodType;\n };\n collapsed?: boolean;\n}\n\ninterface Address {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent | StripePaymentEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport type AddressOptions = Partial
;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\nexport interface TermOptions {\n card?: AutoOrNever;\n}\n\nexport interface StripeLayoutOptions {\n type?: 'accordion' | 'tabs';\n defaultCollapsed?: boolean;\n radios?: boolean;\n spacedAccordionItems?: boolean;\n visibleAccordionItemsCount?: number;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n terms?: TermOptions;\n layout?: StripeLayoutOptions;\n paymentMethodOrder?: string[];\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: Address;\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): Promise;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n fontFamily?: string;\n };\n\n rules?: {\n [key: string]: {\n [key: string]: string | number;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n\n mode?: string;\n amount?: number;\n currency?: string;\n paymentMethodTypes?: string[];\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\nexport interface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n Link = 'link',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n OCS = 'stripe_ocs',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n\nexport enum StripeUPEPaymentIntentStatus {\n REQUIRES_PAYMENT_METHOD = 'requires_payment_method',\n REQUIRES_CONFIRMATION = 'requires_confirmation',\n REQUIRES_ACTION = 'requires_action',\n PROCESSING = 'processing',\n SUCCEEDED = 'succeeded',\n CANCELED = 'canceled',\n}\n\nexport interface StripeUPEPaymentMethod extends PaymentMethod {\n initializationData: StripeUPEInitializationData;\n}\n\nexport interface StripeUPEInitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n shopperLanguage: string;\n newConfirmationFlow?: boolean;\n}\n\nexport interface StripeElementUpdateOptions {\n shouldShowTerms?: boolean;\n}\n\nexport interface StripeAdditionalActionRequired {\n type: string;\n data: {\n token?: string;\n redirect_url?: string;\n };\n}\n\nexport interface StripeAdditionalActionResponseBody {\n additional_action_required: StripeAdditionalActionRequired;\n three_ds_result: {\n token?: string;\n };\n}\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from './stripe-upe';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\nimport { WithStripeUPECustomerInitializeOptions } from './stripeupe-customer-initialize-options';\n\nexport default class StripeUPECustomerStrategy implements CustomerStrategy {\n private _stripeElements?: StripeElements;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithStripeUPECustomerInitializeOptions,\n ): Promise {\n let stripeUPEClient: StripeUPEClient;\n\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { container, gatewayId, methodId, onEmailChange, getStyles, isLoading } =\n options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { clientToken } = paymentMethod;\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod) || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n const { email } = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const stripePaymentProviderCustomer = isStripeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const stripeLinkAuthenticationState =\n stripePaymentProviderCustomer.stripeLinkAuthenticationState;\n\n if (!email) {\n let appearance: StripeUPEAppearanceOptions | undefined;\n const styles = typeof getStyles === 'function' && getStyles();\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {};\n }\n\n stripeUPEClient = await this.scriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n this._stripeElements = await this.scriptLoader.getElements(stripeUPEClient, {\n clientSecret: clientToken,\n appearance,\n });\n\n const { getBillingAddress, getConsignments } =\n this.paymentIntegrationService.getState();\n const consignments = getConsignments();\n const id = consignments?.[0]?.id;\n const { email: billingEmail } = getBillingAddress() || {};\n const options = billingEmail\n ? { defaultValues: { mode: StripeFormMode.SHIPPING, email: billingEmail } }\n : {};\n const linkAuthenticationElement =\n this._stripeElements.getElement(StripeElementType.AUTHENTICATION) ||\n this._stripeElements.create(StripeElementType.AUTHENTICATION, options);\n\n linkAuthenticationElement.on('change', (event: StripeEventType) => {\n if (!('authenticated' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingCustomer);\n }\n\n this.paymentIntegrationService.updatePaymentProviderCustomer({\n stripeLinkAuthenticationState: event.authenticated,\n });\n\n if (event.complete) {\n onEmailChange(event.authenticated, event.value.email);\n } else {\n onEmailChange(false, '');\n }\n\n if (isLoading) {\n isLoading(false);\n }\n\n if (stripeLinkAuthenticationState === undefined && event.authenticated && id) {\n this.paymentIntegrationService.deleteConsignment(id);\n }\n });\n linkAuthenticationElement.mount(`#${container}`);\n }\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.AUTHENTICATION)?.unmount();\n\n return Promise.resolve();\n }\n\n signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n signOut(options?: RequestOptions): Promise {\n this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this.stripeWindow.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this.stripeWindow, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n async getElements(\n stripeClient: StripeUPEClient,\n options: StripeElementsOptions,\n ): Promise {\n let stripeElements = this.stripeWindow.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this.stripeWindow, { bcStripeElements: stripeElements });\n } else {\n await this.updateStripeElements(options);\n }\n\n return stripeElements;\n }\n\n async updateStripeElements(options: StripeElementsOptions) {\n const stripeElements = this.stripeWindow.bcStripeElements;\n\n if (!stripeElements) {\n return;\n }\n\n stripeElements.update(options);\n await stripeElements.fetchUpdates();\n }\n\n private async load() {\n if (!this.stripeWindow.Stripe) {\n await this.scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n return this.stripeWindow.Stripe;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeUPECustomerStrategy from './stripe-upe-customer-strategy';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeUPECustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new StripeUPECustomerStrategy(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeUPECustomerStrategy, [{ id: 'stripeupe' }]);\n","import {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCustomerStrategyFactories from '../generated/customer-strategies';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories = defaultCustomerStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry();\n\n for (const [, createCustomerStrategy] of Object.entries(customerStrategyFactories)) {\n if (\n !isResolvableModule<\n CustomerStrategyFactory,\n CustomerStrategyResolveId\n >(createCustomerStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCustomerStrategy.resolveIds) {\n registry.register(resolverId, () => createCustomerStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { ExecuteSucceededAction, SpamProtectionAction } from './spam-protection-actions';\n\nexport default function isSpamProtectionExecuteSucceededAction(\n action: SpamProtectionAction,\n): action is ExecuteSucceededAction {\n const succeededAction = action as ExecuteSucceededAction;\n\n return (\n typeof succeededAction === 'object' &&\n typeof succeededAction.payload === 'object' &&\n typeof succeededAction.payload.token === 'string'\n );\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadCheckoutAction } from '../checkout';\nimport { SpamProtectionAction } from '../spam-protection';\n\nimport Customer from './customer';\nimport { InternalCustomerResponseData } from './internal-customer-responses';\n\nexport enum CustomerActionType {\n SignInCustomerRequested = 'SIGN_IN_CUSTOMER_REQUESTED',\n SignInCustomerSucceeded = 'SIGN_IN_CUSTOMER_SUCCEEDED',\n SignInCustomerFailed = 'SIGN_IN_CUSTOMER_FAILED',\n\n SignOutCustomerRequested = 'SIGN_OUT_CUSTOMER_REQUESTED',\n SignOutCustomerSucceeded = 'SIGN_OUT_CUSTOMER_SUCCEEDED',\n SignOutCustomerFailed = 'SIGN_OUT_CUSTOMER_FAILED',\n\n CreateCustomerRequested = 'CREATE_CUSTOMER_REQUESTED',\n CreateCustomerSucceeded = 'CREATE_CUSTOMER_SUCCEEDED',\n CreateCustomerFailed = 'CREATE_CUSTOMER_FAILED',\n\n CreateCustomerAddressRequested = 'CREATE_CUSTOMER_ADDRESS_REQUESTED',\n CreateCustomerAddressSucceeded = 'CREATE_CUSTOMER_ADDRESS_SUCCEEDED',\n CreateCustomerAddressFailed = 'CREATE_CUSTOMER_ADDRESS_FAILED',\n\n StripeLinkAuthenticated = 'STRIPE_LINK_AUTHENTICATED',\n}\n\nexport type CustomerAction =\n | SignInCustomerAction\n | SignOutCustomerAction\n | CreateCustomerAddressAction\n | CreateCustomerAction;\n\nexport type CreateCustomerAction =\n | CreateCustomerRequestedAction\n | CreateCustomerSucceededAction\n | CreateCustomerFailedAction\n | SpamProtectionAction\n | LoadCheckoutAction;\n\nexport type CreateCustomerAddressAction =\n | CreateCustomerAddressRequestedAction\n | CreateCustomerAddressSucceededAction\n | CreateCustomerAddressFailedAction\n | LoadCheckoutAction;\n\nexport type SignInCustomerAction =\n | SignInCustomerRequestedAction\n | SignInCustomerSucceededAction\n | SignInCustomerFailedAction\n | LoadCheckoutAction;\n\nexport type SignOutCustomerAction =\n | SignOutCustomerRequestedAction\n | SignOutCustomerSucceededAction\n | SignOutCustomerFailedAction\n | LoadCheckoutAction;\n\nexport interface SignInCustomerRequestedAction extends Action {\n type: CustomerActionType.SignInCustomerRequested;\n}\n\nexport interface StripeLinkAuthenticatedAction extends Action {\n type: CustomerActionType.StripeLinkAuthenticated;\n}\n\nexport interface SignInCustomerSucceededAction extends Action {\n type: CustomerActionType.SignInCustomerSucceeded;\n}\n\nexport interface SignInCustomerFailedAction extends Action {\n type: CustomerActionType.SignInCustomerFailed;\n}\n\nexport interface SignOutCustomerRequestedAction extends Action {\n type: CustomerActionType.SignOutCustomerRequested;\n}\n\nexport interface SignOutCustomerSucceededAction extends Action {\n type: CustomerActionType.SignOutCustomerSucceeded;\n}\n\nexport interface SignOutCustomerFailedAction extends Action {\n type: CustomerActionType.SignOutCustomerFailed;\n}\n\nexport interface CreateCustomerRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerRequested;\n}\n\nexport interface CreateCustomerSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerSucceeded;\n}\n\nexport interface CreateCustomerFailedAction extends Action {\n type: CustomerActionType.CreateCustomerFailed;\n}\n\nexport interface CreateCustomerAddressRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressRequested;\n}\n\nexport interface CreateCustomerAddressSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerAddressSucceeded;\n}\n\nexport interface CreateCustomerAddressFailedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n isSpamProtectionExecuteSucceededAction,\n SpamProtectionActionCreator,\n} from '../spam-protection';\n\nimport CustomerAccountRequestBody, { CustomerAddressRequestBody } from './customer-account';\nimport {\n CreateCustomerAction,\n CreateCustomerAddressAction,\n CustomerActionType,\n SignInCustomerAction,\n SignOutCustomerAction,\n} from './customer-actions';\nimport CustomerCredentials from './customer-credentials';\nimport CustomerRequestSender from './customer-request-sender';\n\nexport default class CustomerActionCreator {\n constructor(\n private _customerRequestSender: CustomerRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n createCustomer(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const config = state.config.getStoreConfigOrThrow();\n const { isStorefrontSpamProtectionEnabled } = config.checkoutSettings;\n\n const createCustomer = (token?: string) =>\n from(\n this._customerRequestSender.createAccount(\n { ...customerAccount, token },\n options,\n ),\n ).pipe(\n switchMap(() =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.CreateCustomerSucceeded)),\n ),\n ),\n );\n\n return concat(\n of(createAction(CustomerActionType.CreateCustomerRequested)),\n isStorefrontSpamProtectionEnabled\n ? from(this._spamProtectionActionCreator.execute()(store)).pipe(\n switchMap((action) =>\n isSpamProtectionExecuteSucceededAction(action)\n ? concat(of(action), createCustomer(action.payload?.token))\n : of(action),\n ),\n )\n : createCustomer(),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerFailed, error),\n ),\n );\n };\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(CustomerActionType.CreateCustomerAddressRequested)),\n defer(async () => {\n const { body } = await this._customerRequestSender.createAddress(\n customerAddress,\n options,\n );\n\n return createAction(CustomerActionType.CreateCustomerAddressSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerAddressFailed, error),\n ),\n );\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(this._customerRequestSender.signInCustomer(credentials, options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.SignInCustomerSucceeded, body.data)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignInCustomerFailed, error),\n ),\n );\n }\n\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(\n createAction(\n CustomerActionType.SignOutCustomerSucceeded,\n body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignOutCustomerFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport Customer from './customer';\nimport { CustomerAccountInternalRequestBody, CustomerAddressRequestBody } from './customer-account';\nimport CustomerCredentials from './customer-credentials';\nimport { InternalCustomerResponseBody } from './internal-customer-responses';\n\nexport default class CustomerRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAccount(\n customerAccount: CustomerAccountInternalRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAccount,\n });\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/customer-address`;\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAddress,\n });\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: credentials,\n });\n }\n\n signOutCustomer({ timeout }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum CustomerStrategyActionType {\n SignInFailed = 'CUSTOMER_STRATEGY_SIGN_IN_FAILED',\n SignInRequested = 'CUSTOMER_STRATEGY_SIGN_IN_REQUESTED',\n SignInSucceeded = 'CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED',\n SignOutFailed = 'CUSTOMER_STRATEGY_SIGN_OUT_FAILED',\n SignOutRequested = 'CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED',\n SignOutSucceeded = 'CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED',\n ExecutePaymentMethodCheckoutFailed = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED',\n ExecutePaymentMethodCheckoutRequested = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED',\n ExecutePaymentMethodCheckoutSucceeded = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED',\n InitializeFailed = 'CUSTOMER_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'CUSTOMER_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'CUSTOMER_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type CustomerStrategyAction =\n | CustomerStrategySignInAction\n | CustomerStrategySignOutAction\n | CustomerStrategyExecutePaymentMethodCheckoutAction\n | CustomerStrategyInitializeAction\n | CustomerStrategyDeinitializeAction\n | CustomerStrategyWidgetAction;\n\nexport type CustomerStrategySignInAction =\n | SignInRequestedAction\n | SignInSucceededAction\n | SignInFailedAction;\n\nexport type CustomerStrategySignOutAction =\n | SignOutRequestedAction\n | SignOutSucceededAction\n | SignOutFailedAction;\n\nexport type CustomerStrategyExecutePaymentMethodCheckoutAction =\n | ExecutePaymentMethodCheckoutRequestedAction\n | ExecutePaymentMethodCheckoutSucceededAction\n | ExecutePaymentMethodCheckoutFailedAction;\n\nexport type CustomerStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type CustomerStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type CustomerStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface SignInRequestedAction extends Action {\n type: CustomerStrategyActionType.SignInRequested;\n}\n\nexport interface SignInSucceededAction extends Action {\n type: CustomerStrategyActionType.SignInSucceeded;\n}\n\nexport interface SignInFailedAction extends Action {\n type: CustomerStrategyActionType.SignInFailed;\n}\n\nexport interface SignOutRequestedAction extends Action {\n type: CustomerStrategyActionType.SignOutRequested;\n}\n\nexport interface SignOutSucceededAction extends Action {\n type: CustomerStrategyActionType.SignOutSucceeded;\n}\n\nexport interface SignOutFailedAction extends Action {\n type: CustomerStrategyActionType.SignOutFailed;\n}\n\nexport interface ExecutePaymentMethodCheckoutRequestedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested;\n}\n\nexport interface ExecutePaymentMethodCheckoutSucceededAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded;\n}\n\nexport interface ExecutePaymentMethodCheckoutFailedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: CustomerStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { CustomerStrategy as CustomerStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport CustomerCredentials from './customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from './customer-request-options';\nimport {\n CustomerStrategyActionType,\n CustomerStrategyDeinitializeAction,\n CustomerStrategyExecutePaymentMethodCheckoutAction,\n CustomerStrategyInitializeAction,\n CustomerStrategySignInAction,\n CustomerStrategySignOutAction,\n CustomerStrategyWidgetAction,\n} from './customer-strategy-actions';\nimport CustomerStrategyRegistryV2 from './customer-strategy-registry-v2';\nimport { CustomerStrategy } from './strategies';\n\nexport default class CustomerStrategyActionCreator {\n constructor(\n private _strategyRegistry: Registry,\n private _strategyRegistryV2: CustomerStrategyRegistryV2,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignInRequested, undefined, meta),\n );\n\n const promise: Promise = this._getStrategy(\n methodId,\n ).signIn(credentials, options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignInSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignInFailed, error, meta),\n );\n });\n });\n }\n\n signOut(options?: CustomerRequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignOutRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).signOut(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignOutSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignOutFailed, error, meta),\n );\n });\n });\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Observable {\n return Observable.create(\n (observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested,\n undefined,\n meta,\n ),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).executePaymentMethodCheckout(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed,\n error,\n meta,\n ),\n );\n });\n },\n );\n }\n\n initialize(\n options?: CustomerInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.InitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).initialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.InitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.InitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n deinitialize(\n options?: CustomerRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && !state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.DeinitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).deinitialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.DeinitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.DeinitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n private _getStrategy(methodId?: string): CustomerStrategy | CustomerStrategyV2 {\n let strategy: CustomerStrategy | CustomerStrategyV2;\n\n try {\n strategy = this._strategyRegistryV2.get({ id: methodId || '' });\n } catch {\n strategy = this._strategyRegistry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import joinIncludes from './join-includes';\nimport mergeIncludes from './merge-includes';\n\n/**\n * Joins or merges a base list of includes with a set of additional includes.\n */\nexport default function joinOrMergeIncludes(\n baseIncludes: T[],\n includeDictionaryOrList: { [key in T]?: boolean } | T[] = [],\n): string {\n return Array.isArray(includeDictionaryOrList)\n ? joinIncludes([...baseIncludes, ...includeDictionaryOrList])\n : mergeIncludes(baseIncludes, includeDictionaryOrList);\n}\n","import { difference, filter, keys, pickBy } from 'lodash';\n\nimport joinIncludes from './join-includes';\n\n/**\n * Merges includes given a list of base includes and a dictionary\n * of includes\n */\nexport default function mergeIncludes(\n baseIncludes: T[],\n includesDictionary?: { [key in T]?: boolean },\n): string {\n const deletions = keys(pickBy(includesDictionary, (on) => !on));\n const additions = keys(filter(includesDictionary));\n\n return joinIncludes([...difference(baseIncludes, deletions), ...additions]);\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport CHECKOUT_DEFAULT_INCLUDES from './checkout-default-includes';\nimport CheckoutParams from './checkout-params';\nimport { CheckoutNotAvailableError } from './errors';\n\nexport default class CheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadCheckout(\n id: string,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender\n .get(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n\n updateCheckout(\n id: string,\n body: CheckoutRequestBody,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadConfigAction } from '../config';\nimport { LoadFormFieldsAction } from '../form';\n\nimport Checkout from './checkout';\n\nexport enum CheckoutActionType {\n LoadCheckoutRequested = 'LOAD_CHECKOUT_REQUESTED',\n LoadCheckoutSucceeded = 'LOAD_CHECKOUT_SUCCEEDED',\n LoadCheckoutFailed = 'LOAD_CHECKOUT_FAILED',\n\n UpdateCheckoutRequested = 'UPDATE_CHECKOUT_REQUESTED',\n UpdateCheckoutSucceeded = 'UPDATE_CHECKOUT_SUCCEEDED',\n UpdateCheckoutFailed = 'UPDATE_CHECKOUT_FAILED',\n}\n\nexport type CheckoutAction = LoadCheckoutAction | UpdateCheckoutAction;\n\nexport type LoadCheckoutAction =\n | LoadCheckoutRequestedAction\n | LoadCheckoutSucceededAction\n | LoadCheckoutFailedAction\n | LoadFormFieldsAction\n | LoadConfigAction;\n\nexport type UpdateCheckoutAction =\n | UpdateCheckoutRequestedAction\n | UpdateCheckoutSucceededAction\n | UpdateCheckoutFailedAction;\n\nexport interface LoadCheckoutRequestedAction extends Action {\n type: CheckoutActionType.LoadCheckoutRequested;\n}\n\nexport interface LoadCheckoutSucceededAction extends Action {\n type: CheckoutActionType.LoadCheckoutSucceeded;\n}\n\nexport interface LoadCheckoutFailedAction extends Action {\n type: CheckoutActionType.LoadCheckoutFailed;\n}\n\nexport interface UpdateCheckoutRequestedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutRequested;\n}\n\nexport interface UpdateCheckoutSucceededAction extends Action {\n type: CheckoutActionType.UpdateCheckoutSucceeded;\n}\n\nexport interface UpdateCheckoutFailedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, merge, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator, StoreConfig } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport default class CheckoutActionCreator {\n constructor(\n private _checkoutRequestSender: CheckoutRequestSender,\n private _configActionCreator: ConfigActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n ) {}\n\n loadCheckout(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n return concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n useCache: true,\n timeout: options?.timeout,\n params: { checkoutId: id },\n }),\n this._formFieldsActionCreator.loadFormFields({\n useCache: true,\n timeout: options?.timeout,\n }),\n ),\n defer(() => {\n return this._checkoutRequestSender\n .loadCheckout(id, options)\n .then(({ body }) => {\n return createAction(\n CheckoutActionType.LoadCheckoutSucceeded,\n this._shouldTransformCustomerAddress(\n store.getState().config.getStoreConfigOrThrow(),\n )\n ? this._transformCustomerAddresses(body)\n : body,\n );\n });\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n };\n }\n\n loadDefaultCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n useCache: true,\n timeout: options?.timeout,\n }),\n this._formFieldsActionCreator.loadFormFields({\n useCache: true,\n timeout: options?.timeout,\n }),\n ),\n defer(async () => {\n const state = store.getState();\n const context = state.config.getContextConfig();\n\n if (!context || !context.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { body } = await this._checkoutRequestSender.loadCheckout(\n context.checkoutId,\n options,\n );\n\n return createAction(\n CheckoutActionType.LoadCheckoutSucceeded,\n this._shouldTransformCustomerAddress(state.config.getStoreConfigOrThrow())\n ? this._transformCustomerAddresses(body)\n : body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n }\n\n updateCheckout(\n body: CheckoutRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CheckoutActionType.UpdateCheckoutRequested));\n\n this._checkoutRequestSender\n .updateCheckout(checkout.id, body, options)\n .then(({ body }) => {\n observer.next(\n createAction(CheckoutActionType.UpdateCheckoutSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CheckoutActionType.UpdateCheckoutFailed, response),\n );\n });\n });\n }\n\n loadCurrentCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this.loadCheckout(checkout.id, options)(store);\n };\n }\n\n private _shouldTransformCustomerAddress(storeConfig: StoreConfig): boolean {\n return (\n storeConfig.checkoutSettings.features[\n 'CHECKOUT-8183.set_shouldSaveAddress_false_for_existing_address'\n ] ?? true\n );\n }\n\n private _transformCustomerAddresses(body: Checkout): Checkout {\n return {\n ...body,\n customer: {\n ...body.customer,\n addresses: body.customer.addresses.map((address) => ({\n ...address,\n shouldSaveAddress: false,\n })),\n },\n };\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { FormFields } from './form-field';\n\nexport enum FormFieldsActionType {\n LoadFormFieldsRequested = 'LOAD_FORM_FIELDS_REQUESTED',\n LoadFormFieldsSucceeded = 'LOAD_FORM_FIELDS_SUCCEEDED',\n LoadFormFieldsFailed = 'LOAD_FORM_FIELDS_FAILED',\n}\n\nexport type LoadFormFieldsAction =\n | LoadFormFieldsRequestedAction\n | LoadFormFieldsSucceededAction\n | LoadFormFieldsFailedAction;\n\nexport interface LoadFormFieldsRequestedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsRequested;\n}\n\nexport interface LoadFormFieldsSucceededAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsSucceeded;\n}\n\nexport interface LoadFormFieldsFailedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsRequestSender from './form-fields-request-sender';\n\nexport default class FormFieldsActionCreator {\n constructor(private _formFieldsRequestSender: FormFieldsRequestSender) {}\n\n @cachableAction\n loadFormFields(options?: RequestOptions & ActionOptions): Observable {\n return concat(\n of(createAction(FormFieldsActionType.LoadFormFieldsRequested)),\n defer(async () => {\n const { body } = await this._formFieldsRequestSender.loadFields(options);\n\n return createAction(FormFieldsActionType.LoadFormFieldsSucceeded, body);\n }),\n ).pipe(\n catchError((response) =>\n throwErrorAction(FormFieldsActionType.LoadFormFieldsFailed, response),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { FormFields } from './form-field';\n\nexport default class FormFieldsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadFields({ timeout }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/form-fields';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport enum PaymentMethodActionType {\n LoadPaymentMethodRequested = 'LOAD_PAYMENT_METHOD_REQUESTED',\n LoadPaymentMethodSucceeded = 'LOAD_PAYMENT_METHOD_SUCCEEDED',\n LoadPaymentMethodFailed = 'LOAD_PAYMENT_METHOD_FAILED',\n\n LoadPaymentMethodsRequested = 'LOAD_PAYMENT_METHODS_REQUESTED',\n LoadPaymentMethodsSucceeded = 'LOAD_PAYMENT_METHODS_SUCCEEDED',\n LoadPaymentMethodsFailed = 'LOAD_PAYMENT_METHODS_FAILED',\n}\n\nexport type PaymentMethodAction = LoadPaymentMethodAction | LoadPaymentMethodsAction;\n\nexport type LoadPaymentMethodAction =\n | LoadPaymentMethodRequestedAction\n | LoadPaymentMethodSucceededAction\n | LoadPaymentMethodFailedAction;\n\nexport type LoadPaymentMethodsAction =\n | LoadPaymentMethodsRequestedAction\n | LoadPaymentMethodsSucceededAction\n | LoadPaymentMethodsFailedAction;\n\nexport interface LoadPaymentMethodRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodRequested;\n}\n\nexport interface LoadPaymentMethodSucceededAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodSucceeded;\n}\n\nexport interface LoadPaymentMethodFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodFailed;\n}\n\nexport interface LoadPaymentMethodsRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsRequested;\n}\n\nexport interface LoadPaymentMethodsSucceededAction\n extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsSucceeded;\n}\n\nexport interface LoadPaymentMethodsFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { filter } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n LoadPaymentMethodAction,\n LoadPaymentMethodsAction,\n PaymentMethodActionType,\n} from './payment-method-actions';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport { isApplePayWindow } from './strategies/apple-pay';\n\nimport { PaymentMethod } from '.';\n\nconst APPLEPAYID = 'applepay';\n\nconst isPaymentMethod = (value: PaymentMethod | undefined): value is PaymentMethod => {\n return !!value;\n};\n\nexport default class PaymentMethodActionCreator {\n constructor(private _requestSender: PaymentMethodRequestSender) {}\n\n loadPaymentMethodsById(\n methodIds: string[],\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n Promise.all(\n methodIds.map(async (id) => {\n try {\n const response = await this._requestSender.loadPaymentMethod(id, {\n ...options,\n params,\n });\n\n return response.body;\n } catch (_e) {\n return undefined;\n }\n }),\n )\n .then((response) => {\n const paymentMethods = response.filter(isPaymentMethod);\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n paymentMethods,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n observer.complete();\n });\n });\n }\n\n loadPaymentMethods(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n\n this._requestSender\n .loadPaymentMethods({\n ...options,\n params: { ...options?.params, cartId: cart.id },\n })\n .then((response) => {\n const meta = {\n deviceSessionId: response.headers['x-device-session-id'],\n sessionHash: response.headers['x-session-hash'],\n };\n const methods = response.body;\n const filteredMethods = Array.isArray(methods)\n ? this._filterApplePay(methods)\n : methods;\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n filteredMethods,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n });\n });\n }\n\n @cachableAction\n loadPaymentMethod(\n methodId: string,\n options?: RequestOptions & ActionOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(\n createAction(PaymentMethodActionType.LoadPaymentMethodRequested, undefined, {\n methodId,\n }),\n );\n\n this._requestSender\n .loadPaymentMethod(methodId, { ...options, params })\n .then((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodSucceeded,\n response.body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n private _filterApplePay(methods: PaymentMethod[]): PaymentMethod[] {\n return filter(methods, (method) => {\n if (method.id === APPLEPAYID && !isApplePayWindow(window)) {\n return false;\n }\n\n return true;\n });\n }\n}\n","export interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport PaymentMethod from './payment-method';\n\nexport default class PaymentMethodRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadPaymentMethods({ timeout, params }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/api/storefront/payments';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n loadPaymentMethod(\n methodId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${methodId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { BuyNowCartRequestBody, Cart } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class CartRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createBuyNowCart(\n body: BuyNowCartRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/carts';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body, headers, timeout });\n }\n}\n","import { isEqual } from 'lodash';\n\nimport { PartialDeep } from '../common/types';\n\nimport Cart from './cart';\n\nexport default class CartComparator {\n isEqual(cartA: Cart, cartB: Cart): boolean {\n return isEqual(this._normalize(cartA), this._normalize(cartB));\n }\n\n private _normalize(cart: Cart): PartialDeep {\n return {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n id: cart.id,\n lineItems: {\n digitalItems: cart.lineItems.digitalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n })),\n giftCertificates: cart.lineItems.giftCertificates\n .slice()\n .sort((itemA, itemB) => `${itemA.id}`.localeCompare(`${itemB.id}`))\n .map((item) => ({\n amount: item.amount,\n recipient: item.recipient,\n })),\n physicalItems: cart.lineItems.physicalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n giftWrapping: item.giftWrapping,\n })),\n },\n };\n }\n}\n","import { ComparableCheckout } from '../../checkout';\nimport { StandardError } from '../../common/error/errors';\n\nexport default class CartChangedError extends StandardError {\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n data: { previous: ComparableCheckout; updated: ComparableCheckout };\n\n constructor(previous: ComparableCheckout, updated: ComparableCheckout) {\n super(\n 'An update to your shopping cart has been detected and your available shipping costs have been updated.',\n );\n\n this.name = 'CartChangedError';\n this.type = 'cart_changed';\n this.data = {\n previous,\n updated,\n };\n }\n}\n","import { isEqual, map } from 'lodash';\n\nimport { Cart, CartComparator } from '../cart';\nimport { CartChangedError } from '../cart/errors';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { Coupon, GiftCertificate } from '../coupon';\n\nimport Checkout from './checkout';\nimport CheckoutRequestSender from './checkout-request-sender';\n\nexport type ComparableCheckout = Pick<\n Checkout,\n 'outstandingBalance' | 'coupons' | 'giftCertificates'\n> & {\n cart: Partial;\n};\n\nexport default class CheckoutValidator {\n constructor(private _checkoutRequestSender: CheckoutRequestSender) {}\n\n validate(checkout?: Checkout, options?: RequestOptions): Promise {\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this._checkoutRequestSender.loadCheckout(checkout.id, options).then((response) => {\n const comparator = new CartComparator();\n\n if (\n checkout.outstandingBalance === response.body.outstandingBalance &&\n this._compareCoupons(checkout.coupons, response.body.coupons) &&\n this._compareGiftCertificates(\n checkout.giftCertificates,\n response.body.giftCertificates,\n ) &&\n comparator.isEqual(checkout.cart, response.body.cart)\n ) {\n return;\n }\n\n throw new CartChangedError(\n this._getComparableCheckout(checkout),\n this._getComparableCheckout(response.body),\n );\n });\n }\n\n private _compareCoupons(couponsA: Coupon[], couponsB: Coupon[]): boolean {\n return isEqual(map(couponsA, 'code'), map(couponsB, 'code'));\n }\n\n private _compareGiftCertificates(\n giftCertificatesA: GiftCertificate[],\n giftCertificatesB: GiftCertificate[],\n ): boolean {\n return isEqual(map(giftCertificatesA, 'code'), map(giftCertificatesB, 'code'));\n }\n\n private _getComparableCheckout(checkout: Checkout): ComparableCheckout {\n const { cart, coupons, giftCertificates, outstandingBalance } = checkout;\n\n return {\n cart: {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n lineItems: cart.lineItems,\n },\n coupons,\n giftCertificates,\n outstandingBalance,\n };\n }\n}\n","import { StandardError } from '../../error/errors';\n\nexport default class UnexpectedDetachmentError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the required element is unexpectedly detached from the page.',\n );\n\n this.name = 'UnexpectedDetachmentError';\n this.type = 'unexpected_detachment';\n }\n}\n","import { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnexpectedDetachmentError } from './errors';\nimport { MutationObserverFactory } from './mutation-observer';\n\nexport default class DetachmentObserver {\n constructor(private _mutationObserver: MutationObserverFactory) {}\n\n async ensurePresence(targets: Node[], promise: Promise): Promise {\n const cancellable = new CancellablePromise(promise);\n\n const observer = this._mutationObserver.create((mutationsList) => {\n mutationsList.forEach((mutation) => {\n const removedTargets = Array.from(mutation.removedNodes).filter((node) =>\n targets.some((target) => node === target || node.contains(target)),\n );\n\n if (removedTargets.length === 0) {\n return;\n }\n\n cancellable.cancel(new UnexpectedDetachmentError());\n });\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n\n try {\n const output = await cancellable.promise;\n\n observer.disconnect();\n\n return output;\n } catch (error) {\n observer.disconnect();\n\n throw error;\n }\n }\n}\n","export interface MutationObeserverCreator {\n prototype: MutationObserver;\n new (callback: MutationCallback): MutationObserver;\n}\n\nexport interface MutationObserverWindow extends Window {\n MutationObserver: MutationObeserverCreator;\n}\n\nexport class MutationObserverFactory {\n constructor(private _window: MutationObserverWindow = window as MutationObserverWindow) {}\n\n create(callback: MutationCallback): MutationObserver {\n return new this._window.MutationObserver(callback);\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Url from './url';\n\nexport default function parseUrl(url: string): Url {\n if (!/^(https?:)?\\/\\//.test(url)) {\n throw new InvalidArgumentError('The provided URL must be absolute.');\n }\n\n // new URL() is not supported in IE11, use anchor tag instead\n const anchor = document.createElement('a');\n\n anchor.href = url;\n\n // IE11 returns 80 or 443 for the port number depending on the URL scheme,\n // even if the port number is not specified in the URL.\n const port =\n anchor.port && url.indexOf(`${anchor.hostname}:${anchor.port}`) !== -1 ? anchor.port : '';\n\n return {\n hash: anchor.hash,\n hostname: anchor.hostname,\n href: anchor.href,\n origin: `${anchor.protocol}//${anchor.hostname}${port ? `:${port}` : ''}`,\n pathname: anchor.pathname,\n port,\n protocol: anchor.protocol,\n search: anchor.search,\n };\n}\n","import IframeEvent from './iframe-event';\n\nexport default function isIframeEvent, TType extends string>(\n object: any,\n type: TType,\n): object is TEvent {\n return object.type === type;\n}\n","import { fromEvent } from 'rxjs';\nimport { filter, map, take } from 'rxjs/operators';\n\nimport { parseUrl } from '../url';\n\nimport IframeEvent from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport interface IframeEventPostOptions<\n TSuccessEvent extends IframeEvent,\n TErrorEvent extends IframeEvent,\n> {\n errorType?: TErrorEvent['type'];\n successType?: TSuccessEvent['type'];\n}\n\nexport default class IframeEventPoster {\n private _targetOrigin: string;\n\n constructor(targetOrigin: string, private _targetWindow?: Window, private _context?: TContext) {\n this._targetOrigin = targetOrigin === '*' ? '*' : parseUrl(targetOrigin).origin;\n }\n\n post(event: TEvent): void;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options: IframeEventPostOptions,\n ): Promise;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options?: IframeEventPostOptions,\n ): Promise | void {\n const targetWindow = this._targetWindow;\n\n if (window === targetWindow) {\n return;\n }\n\n if (!targetWindow) {\n throw new Error('Unable to post message because target window is not set.');\n }\n\n const result =\n options &&\n fromEvent(window, 'message')\n .pipe(\n filter(\n (event) =>\n event.origin === this._targetOrigin &&\n isIframeEvent(event.data, event.data.type) &&\n [options.successType, options.errorType].indexOf(event.data.type) !==\n -1,\n ),\n map((event) => {\n if (options.errorType === event.data.type) {\n throw event.data;\n }\n\n return event.data;\n }),\n take(1),\n )\n .toPromise();\n\n targetWindow.postMessage({ ...event, context: this._context }, this._targetOrigin);\n\n return result;\n }\n\n setTarget(window: Window) {\n this._targetWindow = window;\n }\n\n setContext(context: TContext) {\n this._context = context;\n }\n}\n","import parseUrl from './parse-url';\nimport Url from './url';\n\nexport default function appendWww(url: Url): Url {\n return parseUrl(\n url.hostname.indexOf('www') === 0\n ? url.href\n : url.href.replace(url.hostname, `www.${url.hostname}`),\n );\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { appendWww, parseUrl } from '../url';\n\nimport { IframeEventMap } from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport default class IframeEventListener<\n TEventMap extends IframeEventMap,\n TContext = undefined,\n> {\n private _isListening: boolean;\n private _listeners: EventListeners;\n private _sourceOrigins: string[];\n\n constructor(sourceOrigin: string) {\n this._sourceOrigins = [\n parseUrl(sourceOrigin).origin,\n appendWww(parseUrl(sourceOrigin)).origin,\n ];\n this._isListening = false;\n this._listeners = {};\n }\n\n listen(): void {\n if (this._isListening) {\n return;\n }\n\n this._isListening = true;\n\n window.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n\n window.removeEventListener('message', this._handleMessage);\n }\n\n addListener(\n type: TType,\n listener: (event: TEventMap[TType], context?: TContext) => void,\n ): void {\n let listeners = this._listeners[type];\n\n if (!listeners) {\n this._listeners[type] = listeners = [];\n }\n\n if (listeners.indexOf(listener) === -1) {\n listeners.push(listener);\n }\n }\n\n removeListener(\n type: TType,\n listener: (event: TEventMap[TType], context?: TContext) => void,\n ): void {\n const listeners = this._listeners[type];\n\n if (!listeners) {\n return;\n }\n\n const index = listeners.indexOf(listener);\n\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n }\n\n trigger(event: TEventMap[TType], context?: TContext): void {\n const listeners = this._listeners[event.type];\n\n if (!listeners) {\n return;\n }\n\n listeners.forEach((listener) => (context ? listener(event, context) : listener(event)));\n }\n\n @bind\n private _handleMessage(messageEvent: MessageEvent): void {\n if (\n this._sourceOrigins.indexOf(messageEvent.origin) === -1 ||\n !isIframeEvent(messageEvent.data as TEventMap[keyof TEventMap], messageEvent.data.type)\n ) {\n return;\n }\n\n const { context, ...event } = messageEvent.data;\n\n this.trigger(event, context);\n }\n}\n\ntype EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key], context?: TContext) => void>;\n};\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class SpamProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam protection challenge. Please try again.\");\n\n this.name = 'SpamProtectionChallengeNotCompletedError';\n this.type = 'spam_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class CardingProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super('Please complete our human verification challenge and try again.');\n\n this.name = 'CardingProtectionChallengeNotCompletedError';\n this.type = 'carding_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class CardingProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to verify that you are not a robot. Please try again.');\n\n this.name = 'CardingProtectionFailedError';\n this.type = 'carding_protection_failed';\n }\n}\n","import { switchMap, take } from 'rxjs/operators';\n\nimport { RequestError } from '../common/error/errors';\nimport { PaymentAdditionalAction } from '../payment';\n\nimport {\n CardingProtectionChallengeNotCompletedError,\n CardingProtectionFailedError,\n SpamProtectionChallengeNotCompletedError,\n} from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\n\nexport default class PaymentHumanVerificationHandler {\n constructor(private _googleRecaptcha: GoogleRecaptcha) {}\n\n handle(error: any): Promise;\n handle(id: string, key: string): Promise;\n async handle(errorOrId: Error | string, key?: string): Promise {\n if (typeof errorOrId === 'string') {\n return this.handleWithRecaptchaSitekey(errorOrId, key);\n }\n\n return this.handleWithPaymentHumanVerificationRequestError(errorOrId);\n }\n\n private async handleWithPaymentHumanVerificationRequestError(\n error: Error,\n ): Promise {\n if (!this._isPaymentHumanVerificationRequest(error)) {\n throw error;\n }\n\n await this._initialize(error.body.additional_action_required.data.key);\n\n return this._performRecaptcha();\n }\n\n private async handleWithRecaptchaSitekey(\n id: string,\n key?: string,\n ): Promise {\n if (id !== 'recaptcha_v2') {\n throw Error('Human verification method is not supported.');\n }\n\n if (!key) {\n throw Error('Recaptcha site key is missing.');\n }\n\n await this._initialize(key);\n\n return this._performRecaptcha();\n }\n\n private _performRecaptcha(): Promise {\n return this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw new CardingProtectionChallengeNotCompletedError();\n }\n\n if (error || !token) {\n throw new CardingProtectionFailedError();\n }\n\n return {\n type: 'recaptcha_v2_verification',\n data: {\n human_verification_token: token,\n },\n };\n }),\n )\n .toPromise();\n }\n\n private _initialize(recaptchaSitekey: string): Promise {\n const cardingProtectionElementId = 'cardingProtectionContainer';\n\n let cardingProtectionElement = document.getElementById(cardingProtectionElementId);\n\n if (cardingProtectionElement && cardingProtectionElement.parentNode) {\n cardingProtectionElement.parentNode.removeChild(cardingProtectionElement);\n }\n\n cardingProtectionElement = document.createElement('div');\n cardingProtectionElement.setAttribute('id', cardingProtectionElementId);\n document.body.appendChild(cardingProtectionElement);\n\n return this._googleRecaptcha.load(cardingProtectionElementId, recaptchaSitekey);\n }\n\n private _isPaymentHumanVerificationRequest(error: Error): error is RequestError {\n const { additional_action_required, status } = (error as RequestError).body || {};\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'recaptcha_v2_verification'\n );\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class SpamProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to complete your spam protection verification. Please try again.');\n\n this.name = 'SpamProtectionFailedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if spam protection is not loaded when trying to\n * complete the required spam protection verification.\n */\nexport default class SpamProtectionNotLoadedError extends StandardError {\n constructor() {\n super('Spam protection is not loaded. Please try again.');\n\n this.name = 'SpamProtectionNotLoadedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { defer, Observable, of, Subject, throwError } from 'rxjs';\nimport { catchError, delay, retryWhen, switchMap } from 'rxjs/operators';\n\nimport { MutationObserverFactory } from '../common/dom';\nimport { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport {\n SpamProtectionChallengeNotCompletedError,\n SpamProtectionFailedError,\n SpamProtectionNotLoadedError,\n} from './errors';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nconst TIMEOUT = 7000;\nconst RETRY_INTERVAL = 250;\nconst MAX_RETRIES = TIMEOUT / RETRY_INTERVAL;\n\nexport interface RecaptchaResult {\n error?: Error;\n token?: string;\n}\n\nexport default class GoogleRecaptcha {\n private _event$?: Subject;\n private _recaptcha?: ReCaptchaV2.ReCaptcha;\n private _memoized: (\n recaptcha: ReCaptchaV2.ReCaptcha,\n sitekey: string,\n container: HTMLElement | null,\n ) => Subject;\n private _widgetId?: number;\n\n constructor(\n private googleRecaptchaScriptLoader: GoogleRecaptchaScriptLoader,\n private mutationObserverFactory: MutationObserverFactory,\n ) {\n this._memoized = memoize(\n (recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => {\n const event$ = new Subject();\n\n if (!container) {\n throw new Error();\n }\n\n this._widgetId = recaptcha.render(container.id, {\n sitekey,\n size: 'invisible',\n callback: () => {\n event$.next({\n token: recaptcha.getResponse(this._widgetId),\n });\n recaptcha.reset(this._widgetId);\n },\n 'error-callback': () => {\n event$.next({\n error: new SpamProtectionFailedError(),\n });\n },\n });\n\n return event$;\n },\n { isEqual: (a, b) => a === b },\n );\n }\n\n load(containerId: string, sitekey: string): Promise {\n return this.googleRecaptchaScriptLoader.load().then((recaptcha) => {\n if (recaptcha) {\n this._event$ = this._memoized(\n recaptcha,\n sitekey,\n document.getElementById(containerId),\n );\n this._recaptcha = recaptcha;\n }\n });\n }\n\n execute(): Observable {\n return defer(() => {\n const event$ = this._event$;\n const recaptcha = this._recaptcha;\n\n if (!event$ || !recaptcha) {\n throw new NotInitializedError(NotInitializedErrorType.SpamProtectionNotInitialized);\n }\n\n return defer(() => {\n const element = document.querySelector('iframe[src*=\"bframe\"]');\n\n return element ? of(element) : throwError(new SpamProtectionNotLoadedError());\n }).pipe(\n retryWhen((errors) =>\n errors.pipe(\n delay(RETRY_INTERVAL),\n switchMap((error, index) =>\n index < MAX_RETRIES ? of(error) : throwError(error),\n ),\n ),\n ),\n switchMap((element) => {\n this._watchRecaptchaChallengeWindow(event$, element);\n recaptcha.execute(this._widgetId);\n\n return event$;\n }),\n catchError((error) => of({ error })),\n );\n });\n }\n\n private _watchRecaptchaChallengeWindow(event: Subject, element: Element) {\n const iframeContainer = element.parentElement;\n\n if (!iframeContainer) {\n throw new SpamProtectionNotLoadedError();\n }\n\n const container = iframeContainer.parentElement;\n\n if (!container) {\n throw new SpamProtectionNotLoadedError();\n }\n\n this.mutationObserverFactory\n .create(() => {\n // When customer closes the Google ReCaptcha challenge window, throw SpamProtectionNotCompletedError\n if (container.style.visibility === 'hidden') {\n event.next({\n error: new SpamProtectionChallengeNotCompletedError(),\n });\n }\n })\n .observe(container, { attributes: true, attributeFilter: ['style'] });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nexport default class GoogleRecaptchaScriptLoader {\n private _loadPromise?: Promise;\n\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GoogleRecaptchaWindow = window,\n ) {}\n\n load(): Promise {\n if (!this._loadPromise) {\n this._loadPromise = this._loadScript();\n }\n\n return this._loadPromise;\n }\n\n private _loadScript(): Promise {\n const callbackName = 'initRecaptcha';\n const params = [`onload=${callbackName}`, 'render=explicit'].join('&');\n\n return new Promise((resolve, reject) => {\n this._window[callbackName] = () => resolve(this._window.grecaptcha);\n\n this._scriptLoader\n .loadScript(`//www.google.com/recaptcha/api.js?${params}`)\n .catch((error) => {\n this._loadPromise = undefined;\n reject(error);\n });\n });\n }\n}\n\nexport interface GoogleRecaptchaWindow extends Window {\n grecaptcha?: ReCaptchaV2.ReCaptcha;\n initRecaptcha?(): void;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { MutationObserverFactory } from '../common/dom';\n\nimport GoogleRecaptcha from './google-recaptcha';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nexport default function createSpamProtection(scriptLoader: ScriptLoader): GoogleRecaptcha {\n return new GoogleRecaptcha(\n new GoogleRecaptchaScriptLoader(scriptLoader),\n new MutationObserverFactory(),\n );\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromPaymentErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || message,\n errors,\n });\n}\n\nfunction joinErrors(errors: Array<{ code: string; message?: string }>): string | undefined {\n if (!Array.isArray(errors)) {\n return;\n }\n\n return errors\n .reduce((result: string[], error) => {\n if (error && error.message) {\n return [...result, error.message];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed due to invalid configuration provided for the hosted payment form.',\n );\n\n this.name = 'InvalidHostedFormConfigError';\n this.type = 'invalid_hosted_form_config';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to an unknown error with the hosted payment form.');\n\n this.name = 'InvalidHostedFormError';\n this.type = 'invalid_hosted_form';\n }\n}\n","import { flatMap, map, values } from 'lodash';\n\nimport { StandardError } from '../../common/error/errors';\nimport { HostedInputValidateErrorDataMap } from '../iframe-content';\n\nexport default class InvalidHostedFormValueError extends StandardError {\n constructor(public errors: HostedInputValidateErrorDataMap) {\n super(\n [\n 'Unable to proceed due to invalid user input values',\n ...flatMap(values(errors), (fieldErrors) =>\n map(fieldErrors, ({ message }) => message),\n ),\n ].join('. '),\n );\n\n this.name = 'InvalidHostedFormValueError';\n this.type = 'invalid_hosted_form_value';\n }\n}\n","import { CardInstrument } from '../payment/instrument';\n\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport enum HostedFieldEventType {\n AttachRequested = 'HOSTED_FIELD:ATTACH_REQUESTED',\n SubmitRequested = 'HOSTED_FIELD:SUBMITTED_REQUESTED',\n ValidateRequested = 'HOSTED_FIELD:VALIDATE_REQUESTED',\n StoredCardRequested = 'HOSTED_FIELD:STORED_CARD_REQUESTED',\n}\n\nexport interface HostedFieldEventMap {\n [HostedFieldEventType.AttachRequested]: HostedFieldAttachEvent;\n [HostedFieldEventType.SubmitRequested]: HostedFieldSubmitRequestEvent;\n [HostedFieldEventType.ValidateRequested]: HostedFieldValidateRequestEvent;\n [HostedFieldEventType.StoredCardRequested]: HostedFieldStoredCardRequestEvent;\n}\n\nexport type HostedFieldEvent =\n | HostedFieldAttachEvent\n | HostedFieldSubmitRequestEvent\n | HostedFieldValidateRequestEvent\n | HostedFieldStoredCardRequestEvent;\n\nexport interface HostedFieldAttachEvent {\n type: HostedFieldEventType.AttachRequested;\n payload: {\n accessibilityLabel?: string;\n cardInstrument?: CardInstrument;\n fontUrls?: string[];\n placeholder?: string;\n styles?: HostedFieldStylesMap;\n origin?: string;\n type: HostedFieldType;\n };\n}\n\nexport interface HostedFieldSubmitRequestEvent {\n type: HostedFieldEventType.SubmitRequested;\n payload: {\n data: HostedFormOrderData;\n fields: HostedFieldType[];\n };\n}\n\nexport interface HostedFieldValidateRequestEvent {\n type: HostedFieldEventType.ValidateRequested;\n}\n\nexport interface HostedFieldStoredCardRequestEvent {\n type: HostedFieldEventType.StoredCardRequested;\n payload: {\n data: StoredCardHostedFormData;\n fields: StoredCardHostedFormInstrumentFields;\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport {\n PaymentErrorData,\n PaymentErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HostedFieldType from '../hosted-field-type';\nimport { HostedFormErrorsData } from '../hosted-form-options';\n\nimport HostedInputInitializeErrorData from './hosted-input-initialize-error-data';\nimport HostedInputValidateResults from './hosted-input-validate-results';\n\n// Event types\nexport enum HostedInputEventType {\n AttachSucceeded = 'HOSTED_INPUT:ATTACH_SUCCEEDED',\n AttachFailed = 'HOSTED_INPUT:ATTACH_FAILED',\n BinChanged = 'HOSTED_INPUT:BIN_CHANGED',\n Blurred = 'HOSTED_INPUT:BLURRED',\n Changed = 'HOSTED_INPUT:CHANGED',\n CardTypeChanged = 'HOSTED_INPUT:CARD_TYPE_CHANGED',\n Entered = 'HOSTED_INPUT:ENTERED',\n Focused = 'HOSTED_INPUT:FOCUSED',\n SubmitSucceeded = 'HOSTED_INPUT:SUBMIT_SUCCEEDED',\n SubmitFailed = 'HOSTED_INPUT:SUBMIT_FAILED',\n Validated = 'HOSTED_INPUT:VALIDATED',\n StoredCardSucceeded = 'HOSTED_INPUT:STORED_CARD_SUCCEEDED',\n StoredCardFailed = 'HOSTED_INPUT:STORED_CARD_FAILED',\n}\n\n// Event mapping\nexport interface HostedInputEventMap {\n [HostedInputEventType.AttachSucceeded]: HostedInputAttachSuccessEvent;\n [HostedInputEventType.AttachFailed]: HostedInputAttachErrorEvent;\n [HostedInputEventType.BinChanged]: HostedInputBinChangeEvent;\n [HostedInputEventType.Blurred]: HostedInputBlurEvent;\n [HostedInputEventType.Changed]: HostedInputChangeEvent;\n [HostedInputEventType.CardTypeChanged]: HostedInputCardTypeChangeEvent;\n [HostedInputEventType.Entered]: HostedInputEnterEvent;\n [HostedInputEventType.Focused]: HostedInputFocusEvent;\n [HostedInputEventType.SubmitSucceeded]: HostedInputSubmitSuccessEvent;\n [HostedInputEventType.SubmitFailed]: HostedInputSubmitErrorEvent;\n [HostedInputEventType.Validated]: HostedInputValidateEvent;\n [HostedInputEventType.StoredCardFailed]: HostedInputStoredCardErrorEvent;\n [HostedInputEventType.StoredCardSucceeded]: HostedInputStoredCardSucceededEvent;\n}\n\n// Events\nexport type HostedInputEvent =\n | HostedInputAttachSuccessEvent\n | HostedInputAttachErrorEvent\n | HostedInputBinChangeEvent\n | HostedInputBlurEvent\n | HostedInputChangeEvent\n | HostedInputCardTypeChangeEvent\n | HostedInputEnterEvent\n | HostedInputFocusEvent\n | HostedInputSubmitSuccessEvent\n | HostedInputSubmitErrorEvent\n | HostedInputValidateEvent\n | HostedInputStoredCardSucceededEvent\n | HostedInputStoredCardErrorEvent;\n\nexport interface HostedInputAttachSuccessEvent {\n type: HostedInputEventType.AttachSucceeded;\n}\n\nexport interface HostedInputStoredCardSucceededEvent {\n type: HostedInputEventType.StoredCardSucceeded;\n}\n\nexport interface HostedInputStoredCardErrorEvent {\n type: HostedInputEventType.StoredCardFailed;\n payload?: {\n errors?: string[];\n error?: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputAttachErrorEvent {\n type: HostedInputEventType.AttachFailed;\n payload: {\n error: HostedInputInitializeErrorData;\n };\n}\n\nexport interface HostedInputBinChangeEvent {\n type: HostedInputEventType.BinChanged;\n payload: {\n bin?: string;\n };\n}\n\nexport interface HostedInputBlurEvent {\n type: HostedInputEventType.Blurred;\n payload: {\n fieldType: HostedFieldType;\n errors?: HostedFormErrorsData;\n };\n}\n\nexport interface HostedInputChangeEvent {\n type: HostedInputEventType.Changed;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputCardTypeChangeEvent {\n type: HostedInputEventType.CardTypeChanged;\n payload: {\n cardType?: string;\n };\n}\n\nexport interface HostedInputFocusEvent {\n type: HostedInputEventType.Focused;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputEnterEvent {\n type: HostedInputEventType.Entered;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputSubmitSuccessEvent {\n type: HostedInputEventType.SubmitSucceeded;\n payload: {\n response: Response;\n };\n}\n\nexport interface HostedInputSubmitErrorEvent {\n type: HostedInputEventType.SubmitFailed;\n payload: {\n error: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputValidateEvent {\n type: HostedInputEventType.Validated;\n payload: HostedInputValidateResults;\n}\n","import { values } from 'lodash';\nimport { fromEvent } from 'rxjs';\nimport { switchMap, take } from 'rxjs/operators';\n\nimport { DetachmentObserver } from '../common/dom';\nimport { mapFromPaymentErrorResponse } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { parseUrl } from '../common/url';\nimport { CardInstrument } from '../payment/instrument';\n\nimport {\n InvalidHostedFormConfigError,\n InvalidHostedFormError,\n InvalidHostedFormValueError,\n} from './errors';\nimport { HostedFieldEvent, HostedFieldEventType } from './hosted-field-events';\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputStoredCardSucceededEvent,\n HostedInputSubmitErrorEvent,\n HostedInputSubmitSuccessEvent,\n HostedInputValidateEvent,\n} from './iframe-content';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport const RETRY_INTERVAL = 60 * 1000;\nexport const LAST_RETRY_KEY = 'lastRetry';\n\nexport default class HostedField {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _type: HostedFieldType,\n private _containerId: string,\n private _placeholder: string,\n private _accessibilityLabel: string,\n private _styles: HostedFieldStylesMap,\n private _eventPoster: IframeEventPoster,\n private _eventListener: IframeEventListener,\n private _detachmentObserver: DetachmentObserver,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n this._iframe.src = `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n getType(): HostedFieldType {\n return this._type;\n }\n\n async attach(): Promise {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the provided container ID is not valid.',\n );\n }\n\n container.appendChild(this._iframe);\n this._eventListener.listen();\n\n const promise = fromEvent(this._iframe, 'load')\n .pipe(\n switchMap(async ({ target }) => {\n const contentWindow = target && (target as HTMLIFrameElement).contentWindow;\n\n if (!contentWindow) {\n throw new Error('The content window of the iframe cannot be accessed.');\n }\n\n this._eventPoster.setTarget(contentWindow);\n\n await this._eventPoster.post(\n {\n type: HostedFieldEventType.AttachRequested,\n payload: {\n accessibilityLabel: this._accessibilityLabel,\n cardInstrument: this._cardInstrument,\n fontUrls: this._getFontUrls(),\n placeholder: this._placeholder,\n styles: this._styles,\n origin: document.location.origin,\n type: this._type,\n },\n },\n {\n successType: HostedInputEventType.AttachSucceeded,\n errorType: HostedInputEventType.AttachFailed,\n },\n );\n }),\n take(1),\n )\n .toPromise();\n\n await this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n this._eventListener.stopListen();\n }\n\n async submitForm(\n fields: HostedFieldType[],\n data: HostedFormOrderData,\n ): Promise {\n try {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.SubmitRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.SubmitSucceeded,\n errorType: HostedInputEventType.SubmitFailed,\n },\n );\n\n return await this._detachmentObserver.ensurePresence([this._iframe], promise);\n } catch (event) {\n if (this._isSubmitErrorEvent(event)) {\n if (event.payload.error.code === 'hosted_form_error') {\n throw new InvalidHostedFormError(event.payload.error.message);\n }\n\n if (event.payload.response) {\n throw mapFromPaymentErrorResponse(event.payload.response);\n }\n\n throw new Error(event.payload.error.message);\n }\n\n throw event;\n }\n }\n\n async submitStoredCardForm(\n fields: StoredCardHostedFormInstrumentFields,\n data: StoredCardHostedFormData,\n ): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.StoredCardRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.StoredCardSucceeded,\n errorType: HostedInputEventType.StoredCardFailed,\n },\n );\n\n return this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n async validateForm(): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.ValidateRequested,\n },\n {\n successType: HostedInputEventType.Validated,\n },\n );\n\n const { payload } = await this._detachmentObserver.ensurePresence([this._iframe], promise);\n\n if (!payload.isValid) {\n throw new InvalidHostedFormValueError(payload.errors);\n }\n }\n\n private _getFontUrls(): string[] {\n const hostname = 'fonts.googleapis.com';\n const links = document.querySelectorAll(`link[href*='${hostname}'][rel='stylesheet']`);\n\n return Array.prototype.slice\n .call(links)\n .filter((link) => parseUrl(link.href).hostname === hostname)\n .filter((link) =>\n values(this._styles)\n .map((style) => style && style.fontFamily)\n .filter((family): family is string => typeof family === 'string')\n .some((family) =>\n family\n .split(/,\\s/)\n .some((name) => link.href.indexOf(name.replace(' ', '+')) !== -1),\n ),\n )\n .map((link) => link.href);\n }\n\n private _isSubmitErrorEvent(event: any): event is HostedInputSubmitErrorEvent {\n return event.type === HostedInputEventType.SubmitFailed;\n }\n}\n","import { noop, without } from 'lodash';\n\nimport { HostedForm as HostedFormInterface } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener } from '../common/iframe';\nimport { OrderPaymentRequestBody } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport { InvalidHostedFormConfigError } from './errors';\nimport HostedField from './hosted-field';\nimport LegacyHostedFormOptions from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\nimport {\n HostedInputEnterEvent,\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputStoredCardSucceededEvent,\n HostedInputSubmitSuccessEvent,\n} from './iframe-content';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\ntype HostedFormEventCallbacks = Pick<\n LegacyHostedFormOptions,\n 'onBlur' | 'onCardTypeChange' | 'onFocus' | 'onEnter' | 'onValidate'\n>;\n\nexport default class HostedForm implements HostedFormInterface {\n private _bin?: string;\n private _cardType?: string;\n\n constructor(\n private _fields: HostedField[],\n private _eventListener: IframeEventListener,\n private _payloadTransformer: HostedFormOrderDataTransformer,\n private _eventCallbacks: HostedFormEventCallbacks,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {\n const {\n onBlur = noop,\n onCardTypeChange = noop,\n onFocus = noop,\n onValidate = noop,\n } = this._eventCallbacks;\n\n this._eventListener.addListener(HostedInputEventType.Blurred, ({ payload }) =>\n onBlur(payload),\n );\n this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) =>\n onCardTypeChange(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Focused, ({ payload }) =>\n onFocus(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Validated, ({ payload }) =>\n onValidate(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Entered, this._handleEnter);\n\n this._eventListener.addListener(\n HostedInputEventType.CardTypeChanged,\n ({ payload }) => (this._cardType = payload.cardType),\n );\n this._eventListener.addListener(\n HostedInputEventType.BinChanged,\n ({ payload }) => (this._bin = payload.bin),\n );\n }\n\n getBin(): string | undefined {\n return this._bin;\n }\n\n getCardType(): string | undefined {\n return this._cardType;\n }\n\n async attach(): Promise {\n this._eventListener.listen();\n\n const field = this._getFirstField();\n const otherFields = without(this._fields, field);\n\n await field.attach();\n await Promise.all(otherFields.map((otherField) => otherField.attach()));\n }\n\n detach(): void {\n this._eventListener.stopListen();\n\n this._fields.forEach((field) => {\n field.detach();\n });\n }\n\n async submit(\n payload: OrderPaymentRequestBody,\n additionalActionData?: PaymentAdditionalAction,\n ): Promise {\n try {\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalActionData),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalAction),\n );\n }\n }\n\n async submitStoredCard(payload: {\n fields: StoredCardHostedFormInstrumentFields;\n data: StoredCardHostedFormData;\n }): Promise {\n return this._getFirstField().submitStoredCardForm(payload.fields, payload.data);\n }\n\n async validate(): Promise {\n return this._getFirstField().validateForm();\n }\n\n private _getFirstField(): HostedField {\n const field = this._fields[0];\n\n if (!field) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the payment form has no field defined.',\n );\n }\n\n return field;\n }\n\n private _handleEnter: (event: HostedInputEnterEvent) => Promise = async ({ payload }) => {\n try {\n await this.validate();\n } catch (error) {\n // Catch form validation error because we want to trigger `onEnter`\n // irrespective of the validation result.\n if (error instanceof Error && error.name !== 'InvalidHostedFormValueError') {\n throw error;\n }\n }\n\n const { onEnter = noop } = this._eventCallbacks;\n\n onEnter(payload);\n };\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import { omit } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { OrderPaymentRequestBody } from '../order';\nimport {\n HostedCreditCardInstrument,\n isVaultedInstrument,\n PaymentAdditionalAction,\n} from '../payment';\n\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport default class HostedFormOrderDataTransformer {\n constructor(private _store: ReadableCheckoutStore) {}\n\n transform(\n payload: OrderPaymentRequestBody,\n additionalAction?: PaymentAdditionalAction,\n ): HostedFormOrderData {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const config = state.config.getConfig();\n const instrumentMeta = state.instruments.getInstrumentsMeta();\n const order = state.order.getOrder();\n const orderMeta = state.order.getOrderMeta();\n const payment = omit(\n payload.paymentData,\n 'ccExpiry',\n 'ccName',\n 'ccNumber',\n 'ccCvv',\n ) as HostedCreditCardInstrument;\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n const paymentMethodMeta = state.paymentMethods.getPaymentMethodsMeta();\n const authToken =\n instrumentMeta && payment && isVaultedInstrument(payment)\n ? `${state.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : state.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment,\n paymentMethod,\n paymentMethodMeta,\n };\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\nimport { pick } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { CardInstrument } from '../payment/instrument';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport HostedField from './hosted-field';\nimport HostedFieldType from './hosted-field-type';\nimport HostedForm from './hosted-form';\nimport LegacyHostedFormOptions, {\n HostedCardFieldOptionsMap,\n HostedStoredCardFieldOptionsMap,\n} from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\n\nexport default class HostedFormFactory {\n constructor(private _store: ReadableCheckoutStore) {}\n\n create(host: string, options: LegacyHostedFormOptions): HostedForm {\n const fieldTypes = Object.keys(options.fields) as HostedFieldType[];\n const fields = fieldTypes.reduce((result, type) => {\n const fields = options.fields as HostedStoredCardFieldOptionsMap &\n HostedCardFieldOptionsMap;\n const fieldOptions = fields[type];\n\n if (!fieldOptions) {\n return result;\n }\n\n return [\n ...result,\n new HostedField(\n type,\n fieldOptions.containerId,\n fieldOptions.placeholder || '',\n fieldOptions.accessibilityLabel || '',\n options.styles || {},\n new IframeEventPoster(host),\n new IframeEventListener(host),\n new DetachmentObserver(new MutationObserverFactory()),\n 'instrumentId' in fieldOptions\n ? this._getCardInstrument(fieldOptions.instrumentId)\n : undefined,\n ),\n ];\n }, []);\n\n return new HostedForm(\n fields,\n new IframeEventListener(host),\n new HostedFormOrderDataTransformer(this._store),\n pick(options, 'onBlur', 'onEnter', 'onFocus', 'onCardTypeChange', 'onValidate'),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n }\n\n private _getCardInstrument(instrumentId: string): CardInstrument {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const instrument = getCardInstrument(instrumentId);\n\n if (!instrument) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentInstrument);\n }\n\n return instrument;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam check.\n */\nexport default class SpamProtectionNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam check. Please try again.\");\n\n this.name = 'SpamProtectionNotCompletedError';\n this.type = 'spam_protection_not_completed';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { InternalOrderResponseData } from './internal-order-responses';\nimport Order from './order';\n\nexport enum OrderActionType {\n LoadOrderRequested = 'LOAD_ORDER_REQUESTED',\n LoadOrderSucceeded = 'LOAD_ORDER_SUCCEEDED',\n LoadOrderFailed = 'LOAD_ORDER_FAILED',\n\n LoadOrderPaymentsRequested = 'LOAD_ORDER_PAYMENTS_REQUESTED',\n LoadOrderPaymentsSucceeded = 'LOAD_ORDER_PAYMENTS_SUCCEEDED',\n LoadOrderPaymentsFailed = 'LOAD_ORDER_PAYMENTS_FAILED',\n\n SubmitOrderRequested = 'SUBMIT_ORDER_REQUESTED',\n SubmitOrderSucceeded = 'SUBMIT_ORDER_SUCCEEDED',\n SubmitOrderFailed = 'SUBMIT_ORDER_FAILED',\n\n FinalizeOrderRequested = 'FINALIZE_ORDER_REQUESTED',\n FinalizeOrderSucceeded = 'FINALIZE_ORDER_SUCCEEDED',\n FinalizeOrderFailed = 'FINALIZE_ORDER_FAILED',\n}\n\nexport type OrderAction =\n | LoadOrderAction\n | LoadOrderPaymentsAction\n | SubmitOrderAction\n | FinalizeOrderAction;\n\nexport type LoadOrderPaymentsAction =\n | LoadOrderPaymentsRequestedAction\n | LoadOrderPaymentsSucceededAction\n | LoadOrderPaymentsFailedAction;\n\nexport type LoadOrderAction =\n | LoadOrderRequestedAction\n | LoadOrderSucceededAction\n | LoadOrderFailedAction;\n\nexport type SubmitOrderAction =\n | SubmitOrderRequestedAction\n | SubmitOrderSucceededAction\n | SubmitOrderFailedAction\n | LoadOrderAction;\n\nexport type FinalizeOrderAction =\n | FinalizeOrderRequestedAction\n | FinalizeOrderSucceededAction\n | FinalizeOrderFailedAction\n | LoadOrderAction;\n\nexport interface LoadOrderRequestedAction extends Action {\n type: OrderActionType.LoadOrderRequested;\n}\n\nexport interface LoadOrderSucceededAction extends Action {\n type: OrderActionType.LoadOrderSucceeded;\n}\n\nexport interface LoadOrderFailedAction extends Action {\n type: OrderActionType.LoadOrderFailed;\n}\n\nexport interface LoadOrderPaymentsRequestedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsRequested;\n}\n\nexport interface LoadOrderPaymentsSucceededAction extends Action {\n type: OrderActionType.LoadOrderPaymentsSucceeded;\n}\n\nexport interface LoadOrderPaymentsFailedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsFailed;\n}\n\nexport interface SubmitOrderRequestedAction extends Action {\n type: OrderActionType.SubmitOrderRequested;\n}\n\nexport interface SubmitOrderSucceededAction extends Action {\n type: OrderActionType.SubmitOrderSucceeded;\n}\n\nexport interface SubmitOrderFailedAction extends Action {\n type: OrderActionType.SubmitOrderFailed;\n}\n\nexport interface FinalizeOrderRequestedAction extends Action {\n type: OrderActionType.FinalizeOrderRequested;\n}\n\nexport interface FinalizeOrderSucceededAction extends Action {\n type: OrderActionType.FinalizeOrderSucceeded;\n}\n\nexport interface FinalizeOrderFailedAction extends Action {\n type: OrderActionType.FinalizeOrderFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, Observer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutValidator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { SpamProtectionNotCompletedError } from '../spam-protection/errors';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport {\n FinalizeOrderAction,\n LoadOrderAction,\n LoadOrderPaymentsAction,\n OrderActionType,\n SubmitOrderAction,\n} from './order-actions';\nimport OrderRequestBody from './order-request-body';\nimport OrderRequestSender from './order-request-sender';\n\nexport default class OrderActionCreator {\n constructor(\n private _orderRequestSender: OrderRequestSender,\n private _checkoutValidator: CheckoutValidator,\n ) {}\n\n loadOrder(orderId: number, options?: RequestOptions): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(createAction(OrderActionType.LoadOrderSucceeded, response.body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(OrderActionType.LoadOrderFailed, response));\n });\n });\n }\n\n // TODO: Remove when checkout does not contain unrelated order data.\n loadOrderPayments(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderPaymentsRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(\n createAction(OrderActionType.LoadOrderPaymentsSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(OrderActionType.LoadOrderPaymentsFailed, response),\n );\n });\n });\n }\n\n loadCurrentOrder(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n defer(() => {\n const orderId = this._getCurrentOrderId(store.getState());\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.loadOrder(orderId, options);\n });\n }\n\n submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(OrderActionType.SubmitOrderRequested)),\n defer(() => {\n const state = store.getState();\n const externalSource = state.config.getExternalSource();\n const variantIdentificationToken = state.config.getVariantIdentificationToken();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (checkout.shouldExecuteSpamCheck) {\n throw new SpamProtectionNotCompletedError();\n }\n\n return from(\n this._checkoutValidator.validate(checkout, options).then(() =>\n this._orderRequestSender.submitOrder(\n this._mapToOrderRequestBody(\n payload ?? {},\n checkout.id,\n checkout.customerMessage,\n externalSource,\n ),\n {\n ...options,\n headers: {\n checkoutVariant: variantIdentificationToken,\n },\n },\n ),\n ),\n ).pipe(\n switchMap((response) =>\n concat(\n // TODO: Remove once we can submit orders using storefront API\n this.loadOrder(response.body.data.order.orderId, options),\n of(\n createAction(\n OrderActionType.SubmitOrderSucceeded,\n response.body.data,\n { ...response.body.meta, token: response.headers.token },\n ),\n ),\n ),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(OrderActionType.SubmitOrderFailed, error),\n ),\n ),\n );\n }\n\n finalizeOrder(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(OrderActionType.FinalizeOrderRequested)),\n from(this._orderRequestSender.finalizeOrder(orderId, options)).pipe(\n switchMap((response) =>\n concat(\n this.loadOrder(orderId, options),\n of(\n createAction(\n OrderActionType.FinalizeOrderSucceeded,\n response.body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(catchError((error) => throwErrorAction(OrderActionType.FinalizeOrderFailed, error)));\n }\n\n private _getCurrentOrderId(state: InternalCheckoutSelectors): number | undefined {\n const order = state.order.getOrder();\n const checkout = state.checkout.getCheckout();\n\n return (order && order.orderId) || (checkout && checkout.orderId);\n }\n\n private _mapToOrderRequestBody(\n payload: OrderRequestBody,\n cartId: string,\n customerMessage: string,\n externalSource?: string,\n ): InternalOrderRequestBody {\n const { payment, ...order } = payload;\n\n if (!payment) {\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n };\n }\n\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n payment: {\n paymentData: payment.paymentData,\n name: payment.methodId,\n gateway: payment.gatewayId,\n },\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when the server detects inconsistency in cart data since it is last requested,\n * for example, product prices or eligible discounts have changed.\n */\nexport default class CartConsistencyError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because some details have changed. Please review your order and try again.',\n );\n\n this.name = 'CartConsistencyError';\n this.type = 'cart_consistency';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Checkout prevents consumers from placing their orders when a merchant wishes\n * to be able to block transactions if the automated tax provider cannot be reached.\n */\nexport default class OrderTaxProviderUnavailableError extends StandardError {\n constructor(message?: string) {\n super(message || 'The tax provider is unavailable.');\n\n this.name = 'OrderTaxProviderUnavailableError';\n this.type = 'tax_provider_unavailable';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport { CartConsistencyError } from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { OrderTaxProviderUnavailableError } from './errors';\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { InternalOrderResponseBody } from './internal-order-responses';\nimport Order from './order';\n\nexport interface SubmitOrderRequestOptions extends RequestOptions {\n headers?: {\n checkoutVariant?: string;\n };\n}\n\nexport default class OrderRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadOrder(orderId: number, { timeout }: RequestOptions = {}): Promise> {\n const url = `/api/storefront/orders/${orderId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = [\n 'payments',\n 'lineItems.physicalItems.socialMedia',\n 'lineItems.physicalItems.options',\n 'lineItems.physicalItems.categories',\n 'lineItems.digitalItems.socialMedia',\n 'lineItems.digitalItems.options',\n 'lineItems.digitalItems.categories',\n ];\n\n return this._requestSender.get(url, {\n params: {\n include: joinIncludes(include),\n },\n headers,\n timeout,\n });\n }\n\n submitOrder(\n body?: InternalOrderRequestBody,\n { headers, timeout }: SubmitOrderRequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/order';\n\n return this._requestSender\n .post(url, {\n body,\n headers: omitBy(\n {\n 'X-Checkout-Variant': headers && headers.checkoutVariant,\n ...SDK_VERSION_HEADERS,\n },\n isNil,\n ),\n timeout,\n })\n .catch((error) => {\n if (error.body.type === 'tax_provider_unavailable') {\n throw new OrderTaxProviderUnavailableError();\n }\n\n if (error.body.type === 'cart_has_changed') {\n throw new CartConsistencyError();\n }\n\n throw error;\n });\n }\n\n finalizeOrder(\n orderId: number,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/internalapi/v1/checkout/order/${orderId}`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderAction } from '../order';\n\nimport PaymentResponseBody from './payment-response-body';\n\nexport enum PaymentActionType {\n SubmitPaymentRequested = 'SUBMIT_PAYMENT_REQUESTED',\n SubmitPaymentSucceeded = 'SUBMIT_PAYMENT_SUCCEEDED',\n SubmitPaymentFailed = 'SUBMIT_PAYMENT_FAILED',\n\n InitializeOffsitePaymentRequested = 'INITIALIZE_OFFSITE_PAYMENT_REQUESTED',\n InitializeOffsitePaymentSucceeded = 'INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED',\n InitializeOffsitePaymentFailed = 'INITIALIZE_OFFSITE_PAYMENT_FAILED',\n}\n\nexport type PaymentAction = SubmitPaymentAction | InitializeOffsitePaymentAction;\n\nexport type SubmitPaymentAction =\n | SubmitPaymentRequestedAction\n | SubmitPaymentSucceededAction\n | SubmitPaymentFailedAction\n | LoadOrderAction;\n\nexport type InitializeOffsitePaymentAction =\n | InitializeOffsitePaymentRequestedAction\n | InitializeOffsitePaymentSucceededAction\n | InitializeOffsitePaymentFailedAction;\n\nexport interface SubmitPaymentRequestedAction extends Action {\n type: PaymentActionType.SubmitPaymentRequested;\n}\n\nexport interface SubmitPaymentSucceededAction extends Action {\n type: PaymentActionType.SubmitPaymentSucceeded;\n}\n\nexport interface SubmitPaymentFailedAction extends Action {\n type: PaymentActionType.SubmitPaymentFailed;\n}\n\nexport interface InitializeOffsitePaymentRequestedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentRequested;\n}\n\nexport interface InitializeOffsitePaymentSucceededAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentSucceeded;\n}\n\nexport interface InitializeOffsitePaymentFailedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { OrderActionCreator } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport Payment, {\n FormattedHostedInstrument,\n FormattedPayload,\n FormattedVaultedInstrument,\n} from './payment';\nimport {\n InitializeOffsitePaymentAction,\n PaymentActionType,\n SubmitPaymentAction,\n} from './payment-actions';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\n\ninterface InitializeOffsitePaymentSettings {\n methodId: string;\n gatewayId?: string;\n instrumentId?: string;\n target?: string;\n promise?: Promise;\n shouldSaveInstrument?: boolean;\n shouldSetAsDefaultInstrument?: boolean;\n}\n\ntype InitializeOffsitePayment = (\n settings: InitializeOffsitePaymentSettings,\n) => ThunkAction;\n\nexport default class PaymentActionCreator {\n constructor(\n private _paymentRequestSender: PaymentRequestSender,\n private _orderActionCreator: OrderActionCreator,\n private _paymentRequestTransformer: PaymentRequestTransformer,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n submitPayment(payment: Payment): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentActionType.SubmitPaymentRequested)),\n defer(async () => {\n try {\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(payment, store.getState()),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(\n error,\n );\n\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(\n { ...payment, additionalAction },\n store.getState(),\n ),\n );\n }\n }).pipe(\n switchMap(({ body }) =>\n concat(\n this._orderActionCreator.loadCurrentOrder()(store),\n of(createAction(PaymentActionType.SubmitPaymentSucceeded, body)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.SubmitPaymentFailed, error),\n ),\n );\n }\n\n initializeOffsitePayment: InitializeOffsitePayment = ({\n methodId,\n gatewayId,\n instrumentId,\n target,\n promise,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n }) => {\n return (store) => {\n let paymentData:\n | FormattedPayload\n | undefined;\n\n if (instrumentId) {\n paymentData = { formattedPayload: { bigpay_token: instrumentId } };\n } else if (shouldSaveInstrument) {\n paymentData = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n };\n }\n\n const payload = this._paymentRequestTransformer.transform(\n { gatewayId, methodId, paymentData },\n store.getState(),\n );\n\n return concat(\n of(createAction(PaymentActionType.InitializeOffsitePaymentRequested)),\n Promise.race(\n [\n this._paymentRequestSender.initializeOffsitePayment(payload, target),\n promise,\n ].filter(Boolean),\n ).then(() => createAction(PaymentActionType.InitializeOffsitePaymentSucceeded)),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.InitializeOffsitePaymentFailed, error),\n ),\n );\n };\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentRequestBody from './payment-request-body';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class PaymentRequestSender {\n /**\n * @class\n * @param {BigpayClient} client\n */\n constructor(private _client: any) {}\n\n submitPayment(payload: PaymentRequestBody): Promise> {\n return new Promise((resolve, reject) => {\n this._client.submitPayment(payload, (error: any, response: any) => {\n if (error) {\n reject(this._transformResponse(error));\n } else {\n resolve(this._transformResponse(response));\n }\n });\n });\n }\n\n initializeOffsitePayment(payload: PaymentRequestBody, target?: string): Promise {\n return new Promise(() => {\n this._client.initializeOffsitePayment(payload, null, target);\n });\n }\n\n private _transformResponse(response: any): Response {\n return {\n headers: response.headers,\n body: response.data,\n status: response.status,\n statusText: response.statusText,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/bigpay-client\");","// / \nimport { createClient as createBigpayClient } from '@bigcommerce/bigpay-client';\n\nimport { CheckoutStore } from '../checkout';\n\nexport default function createPaymentClient(store: CheckoutStore) {\n const paymentClient = createBigpayClient();\n\n store.subscribe(\n (state) => {\n const config = state.config.getStoreConfig();\n\n if (config) {\n paymentClient.setHost(config.paymentSettings.bigpayBaseUrl);\n }\n },\n (state) => state.config.getStoreConfig(),\n );\n\n return paymentClient;\n}\n","import { BillingAddress, isBillingAddressLike } from '../billing';\nimport { Consignment } from '../shipping';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalAddress(\n address: Address | BillingAddress,\n consignments?: Consignment[],\n): InternalAddress {\n let addressId;\n\n if (isBillingAddressLike(address)) {\n addressId = address.id;\n } else if (consignments && consignments.length) {\n addressId = consignments[0].id;\n }\n\n return {\n id: addressId,\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n addressLine1: address.address1,\n addressLine2: address.address2,\n city: address.city,\n province: address.stateOrProvince,\n provinceCode: address.stateOrProvinceCode,\n postCode: address.postalCode,\n country: address.country,\n countryCode: address.countryCode,\n phone: address.phone,\n customFields: address.customFields,\n };\n}\n","import { Address } from '../address';\n\nimport BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: Address): address is BillingAddress {\n const billingAddress = address as BillingAddress;\n\n return typeof billingAddress.id !== 'undefined';\n}\n","export default class AmountTransformer {\n constructor(private _decimalPlaces: number) {}\n\n toInteger(amount: number): number {\n return Math.round(amount * 10 ** this._decimalPlaces);\n }\n}\n","import Coupon from './coupon';\nimport InternalCoupon from './internal-coupon';\n\nconst couponTypes = [\n 'per_item_discount',\n 'percentage_discount',\n 'per_total_discount',\n 'shipping_discount',\n 'free_shipping',\n];\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {\n return {\n code: coupon.code,\n discount: coupon.displayName,\n discountType: couponTypes.indexOf(coupon.couponType),\n };\n}\n","import GiftCertificate from './gift-certificate';\nimport InternalGiftCertificate from './internal-gift-certificate';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalGiftCertificate(\n giftCertificate: GiftCertificate,\n): InternalGiftCertificate {\n return {\n code: giftCertificate.code,\n discountedAmount: giftCertificate.used,\n remainingBalance: giftCertificate.remaining,\n giftCertificate: {\n balance: giftCertificate.balance,\n code: giftCertificate.code,\n purchaseDate: giftCertificate.purchaseDate,\n },\n };\n}\n","enum CheckoutButtonMethodType {\n APPLEPAY = \"applepay\",\n AMAZON_PAY_V2 = \"amazonpay\",\n BRAINTREE_PAYPAL = \"braintreepaypal\",\n BRAINTREE_VENMO = \"braintreevenmo\",\n BRAINTREE_PAYPAL_CREDIT = \"braintreepaypalcredit\",\n GOOGLEPAY_ADYENV2 = \"googlepayadyenv2\",\n GOOGLEPAY_ADYENV3 = \"googlepayadyenv3\",\n GOOGLEPAY_AUTHORIZENET = \"googlepayauthorizenet\",\n GOOGLEPAY_BNZ = \"googlepaybnz\",\n GOOGLEPAY_BRAINTREE = \"googlepaybraintree\",\n GOOGLEPAY_CHECKOUTCOM = \"googlepaycheckoutcom\",\n GOOGLEPAY_CYBERSOURCEV2 = \"googlepaycybersourcev2\",\n GOOGLEPAY_ORBITAL = \"googlepayorbital\",\n GOOGLEPAY_STRIPE = \"googlepaystripe\",\n GOOGLEPAY_STRIPEUPE = \"googlepaystripeupe\",\n GOOGLEPAY_WORLDPAYACCESS = \"googlepayworldpayaccess\",\n MASTERPASS = \"masterpass\",\n PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\n\n","import InternalLineItem from './internal-line-item';\nimport { LineItem } from './line-item';\nimport LineItemMap from './line-item-map';\nimport mapGiftCertificateToInternalLineItem from './map-gift-certificate-to-internal-line-item';\nimport mapToInternalLineItem from './map-to-internal-line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItems(\n itemMap: LineItemMap,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem[] {\n return (Object.keys(itemMap) as Array).reduce(\n (result, key) => [\n ...result,\n ...(itemMap[key] as LineItem[]).map((item: any) => {\n if (key === 'giftCertificates') {\n return mapGiftCertificateToInternalLineItem(item, decimalPlaces);\n }\n\n return mapToInternalLineItem(\n item,\n mapToInternalLineItemType(key),\n decimalPlaces,\n idKey,\n );\n }),\n ],\n [] as InternalLineItem[],\n );\n}\n\nfunction mapToInternalLineItemType(type: string): string {\n switch (type) {\n case 'physicalItems':\n return 'ItemPhysicalEntity';\n\n case 'digitalItems':\n return 'ItemDigitalEntity';\n\n case 'giftCertificates':\n return 'ItemGiftCertificateEntity';\n\n default:\n return '';\n }\n}\n","import { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport InternalLineItem from './internal-line-item';\nimport { GiftCertificateItem } from './line-item';\n\nexport default function mapGiftCertificateToInternalLineItem(\n item: GiftCertificateItem,\n decimalPlaces: number,\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item.id,\n imageUrl: '',\n name: item.name,\n amount: item.amount,\n amountAfterDiscount: item.amount,\n discount: 0,\n integerAmount: amountTransformer.toInteger(item.amount),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.amount),\n integerUnitPrice: amountTransformer.toInteger(item.amount),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.amount),\n integerDiscount: 0,\n quantity: 1,\n sender: item.sender,\n recipient: item.recipient,\n type: 'ItemGiftCertificateEntity',\n attributes: [],\n variantId: null,\n };\n}\n","import { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport InternalLineItem from './internal-line-item';\nimport { DigitalItem, LineItem } from './line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItem(\n item: LineItem,\n type: string,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item[idKey] as string | number,\n imageUrl: item.imageUrl,\n amount: item.extendedListPrice,\n amountAfterDiscount: item.extendedSalePrice,\n discount: item.discountAmount,\n integerAmount: amountTransformer.toInteger(item.extendedListPrice),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.extendedSalePrice),\n integerDiscount: amountTransformer.toInteger(item.discountAmount),\n integerUnitPrice: amountTransformer.toInteger(item.listPrice),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.salePrice),\n downloadsPageUrl: (item as DigitalItem).downloadPageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: item.brand,\n sku: item.sku,\n categoryNames: item.categoryNames,\n variantId: item.variantId,\n productId: item.productId,\n attributes: (item.options || []).map((option) => ({\n name: option.name,\n value: option.value,\n })),\n addedByPromotion: item.addedByPromotion,\n type,\n };\n}\n","import { keyBy, reduce, some } from 'lodash';\n\nimport { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { mapToInternalCoupon, mapToInternalGiftCertificate } from '../coupon';\nimport { mapToDiscountNotifications } from '../promotion';\n\nimport InternalCart from './internal-cart';\nimport mapToInternalLineItems from './map-to-internal-line-items';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCart(checkout: Checkout): InternalCart {\n const decimalPlaces = checkout.cart.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: checkout.cart.id,\n items: mapToInternalLineItems(checkout.cart.lineItems, decimalPlaces),\n currency: checkout.cart.currency.code,\n coupon: {\n discountedAmount: reduce(\n checkout.cart.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: checkout.cart.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: checkout.cart.discountAmount,\n integerAmount: amountTransformer.toInteger(checkout.cart.discountAmount),\n },\n discountNotifications: mapToDiscountNotifications(checkout.promotions),\n giftCertificate: {\n totalDiscountedAmount: reduce(\n checkout.giftCertificates,\n (sum, certificate) => {\n return sum + certificate.used;\n },\n 0,\n ),\n appliedGiftCertificates: keyBy(\n checkout.giftCertificates.map(mapToInternalGiftCertificate),\n 'code',\n ),\n },\n shipping: {\n amount: checkout.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.shippingCostTotal),\n amountBeforeDiscount: checkout.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n checkout.shippingCostBeforeDiscount,\n ),\n required: some(\n checkout.cart.lineItems.physicalItems,\n (lineItem) => lineItem.isShippingRequired,\n ),\n },\n subtotal: {\n amount: checkout.subtotal,\n integerAmount: amountTransformer.toInteger(checkout.subtotal),\n },\n storeCredit: {\n amount: checkout.customer ? checkout.customer.storeCredit : 0,\n },\n taxSubtotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n taxes: checkout.taxes,\n taxTotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n handling: {\n amount: checkout.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.handlingCostTotal),\n },\n grandTotal: {\n amount: checkout.grandTotal,\n integerAmount: amountTransformer.toInteger(checkout.grandTotal),\n },\n };\n}\n","import { DiscountNotification } from '../discount';\n\nimport { Promotion } from '.';\n\nexport default function mapToDiscountNotifications(\n promotions?: Promotion[],\n): DiscountNotification[] {\n const notifications: DiscountNotification[] = [];\n\n (promotions || []).forEach((promotion) => {\n (promotion.banners || []).forEach((banner) => {\n notifications.push({\n placeholders: [],\n discountType: null,\n message: '',\n messageHtml: banner.text,\n });\n });\n });\n\n return notifications;\n}\n","import { mapToInternalAddress } from '../address';\nimport { OrderBillingAddress } from '../order-billing-address/order-billing-address-state';\n\nimport InternalCustomer from './internal-customer';\n\nimport { Customer } from '.';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCustomer(\n customer: Customer,\n billingAddress: OrderBillingAddress,\n): InternalCustomer {\n const firstName = customer.firstName || billingAddress.firstName || '';\n const lastName = customer.lastName || billingAddress.lastName || '';\n\n return {\n addresses: (customer.addresses || []).map((address) => mapToInternalAddress(address)),\n customerId: customer.id,\n isGuest: customer.isGuest,\n storeCredit: customer.storeCredit,\n email: customer.email || billingAddress.email || '',\n firstName,\n lastName,\n name: customer.fullName || [firstName, lastName].join(' '),\n customerGroupName: customer.customerGroup && customer.customerGroup.name,\n };\n}\n","import CardExpiryDate from './card-expiry-date';\n\nconst NUMBER_SEPARATOR = '/';\n\nexport default class CardExpiryFormatter {\n format(value: string): string {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n const trimmedMonth = month.slice(0, 2);\n const trimmedYear =\n year.length === 4 ? year.slice(-2) : year ? year.slice(0, 2) : month.slice(2);\n\n // i.e.: '1'\n if (value.length < 2) {\n return month;\n }\n\n // ie.: '10 /' (without trailing space)\n if (value.length > 3 && !trimmedYear) {\n return trimmedMonth;\n }\n\n return `${trimmedMonth} ${NUMBER_SEPARATOR} ${trimmedYear}`;\n }\n\n toObject(value: string): CardExpiryDate {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n\n if (!/^\\d+$/.test(month) || !/^\\d+$/.test(year)) {\n return { month: '', year: '' };\n }\n\n return {\n month: month.length === 1 ? `0${month}` : month.slice(0, 2),\n year: year.length === 2 ? `20${year}` : year.slice(0, 4),\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"card-validator\");","import { creditCardType, number } from 'card-validator';\nimport { max } from 'lodash';\n\nconst NUMBER_SEPARATOR = ' ';\n\nexport default class CardNumberFormatter {\n format(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n const maxLength = max(creditCardType(value).map((info) => max(info.lengths)));\n const unformattedValue = this.unformat(value).slice(0, maxLength);\n\n return card.gaps\n .filter((gapIndex) => unformattedValue.length > gapIndex)\n .reduce(\n (output, gapIndex, index) =>\n [output.slice(0, gapIndex + index), output.slice(gapIndex + index)].join(\n NUMBER_SEPARATOR,\n ),\n unformattedValue,\n );\n }\n\n unformat(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n return value.replace(new RegExp(NUMBER_SEPARATOR, 'g'), '');\n }\n}\n","import { filter, find, keyBy, reduce } from 'lodash';\n\nimport { AmountTransformer } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { LineItem, mapToInternalLineItems } from '../cart';\nimport { Checkout } from '../checkout';\nimport { mapToInternalCoupon } from '../coupon';\nimport { HOSTED } from '../payment';\n\nimport InternalOrder, {\n InternalGiftCertificateList,\n InternalIncompleteOrder,\n InternalOrderPayment,\n InternalSocialDataList,\n} from './internal-order';\nimport Order, {\n GatewayOrderPayment,\n GiftCertificateOrderPayment,\n OrderPayment,\n OrderPayments,\n} from './order';\nimport { OrderMetaState } from './order-state';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalOrder(\n order: Order,\n orderMeta: OrderMetaState = {},\n): InternalOrder {\n const decimalPlaces = order.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: order.orderId,\n items: mapToInternalLineItems(order.lineItems, order.currency.decimalPlaces, 'productId'),\n orderId: order.orderId,\n currency: order.currency.code,\n customerCanBeCreated: order.customerCanBeCreated,\n payment: mapToInternalOrderPayment(order.payments, orderMeta.payment),\n subtotal: {\n amount: order.baseAmount,\n integerAmount: amountTransformer.toInteger(order.baseAmount),\n },\n coupon: {\n discountedAmount: reduce(\n order.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: order.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: order.discountAmount,\n integerAmount: amountTransformer.toInteger(order.discountAmount),\n },\n token: orderMeta.orderToken,\n callbackUrl: orderMeta.callbackUrl,\n discountNotifications: [],\n giftCertificate: mapToGiftCertificates(order.payments),\n socialData: mapToInternalSocialDataList(order),\n status: order.status,\n hasDigitalItems: order.hasDigitalItems,\n isDownloadable: order.isDownloadable,\n isComplete: order.isComplete,\n shipping: {\n amount: order.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(order.shippingCostTotal),\n amountBeforeDiscount: order.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n order.shippingCostBeforeDiscount,\n ),\n },\n storeCredit: {\n amount: mapToStoreCredit(order.payments),\n },\n taxes: order.taxes,\n taxTotal: {\n amount: order.taxTotal,\n integerAmount: amountTransformer.toInteger(order.taxTotal),\n },\n handling: {\n amount: order.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(order.handlingCostTotal),\n },\n grandTotal: {\n amount: order.orderAmount,\n integerAmount: order.orderAmountAsInteger,\n },\n };\n}\n\nexport function mapToInternalIncompleteOrder(checkout: Checkout): InternalIncompleteOrder {\n const payment = find(checkout.payments, { providerType: HOSTED });\n\n return {\n orderId: null,\n isComplete: false,\n payment: !payment\n ? {}\n : {\n id: payment.providerId,\n gateway: payment.gatewayId,\n status: mapToInternalPaymentStatus(payment.detail.step),\n },\n };\n}\n\nfunction mapToInternalPaymentStatus(status: string): string {\n return `PAYMENT_STATUS_${status}`;\n}\n\nfunction mapToStoreCredit(payments?: OrderPayments): number {\n const item = find(payments, { providerId: 'storecredit' });\n\n return item ? item.amount : 0;\n}\n\nfunction mapToGiftCertificates(payments?: OrderPayments): InternalGiftCertificateList {\n const items = filter(payments, {\n providerId: 'giftcertificate',\n }) as GiftCertificateOrderPayment[];\n\n return {\n totalDiscountedAmount: reduce(items, (sum, item) => item.amount + sum, 0),\n appliedGiftCertificates: keyBy(\n items.map((item) => ({\n code: item.detail.code,\n discountedAmount: item.amount,\n remainingBalance: item.detail.remaining,\n giftCertificate: {\n balance: item.amount + item.detail.remaining,\n code: item.detail.code,\n purchaseDate: '',\n },\n })),\n 'code',\n ),\n };\n}\n\nfunction mapToInternalOrderPayment(\n payments?: OrderPayments,\n payment: InternalOrderPayment = {},\n): InternalOrderPayment {\n const item = find(payments, isDefaultOrderPayment) as GatewayOrderPayment;\n\n if (!item) {\n return {};\n }\n\n return {\n id: item.providerId,\n status: mapToInternalPaymentStatus(item.detail.step),\n helpText: item.detail.instructions,\n returnUrl: payment.returnUrl,\n };\n}\n\nfunction isDefaultOrderPayment(payment: OrderPayment): payment is GatewayOrderPayment {\n return payment.providerId !== 'giftcertificate' && payment.providerId !== 'storecredit';\n}\n\nfunction mapToInternalSocialDataList(\n order: Order,\n): { [itemId: string]: InternalSocialDataList } | undefined {\n const socialDataObject: { [itemId: string]: InternalSocialDataList } = {};\n const items = [...order.lineItems.physicalItems, ...order.lineItems.digitalItems];\n\n items.forEach((item) => {\n socialDataObject[item.id] = mapToInternalSocialData(item);\n });\n\n return socialDataObject;\n}\n\nfunction mapToInternalSocialData(lineItem: LineItem): InternalSocialDataList {\n const codes = ['fb', 'tw', 'gp'];\n\n return codes.reduce((socialData, code) => {\n const item =\n lineItem.socialMedia && find(lineItem.socialMedia, (item) => item.code === code);\n\n if (!item) {\n return socialData;\n }\n\n socialData[code] = {\n name: lineItem.name,\n description: lineItem.name,\n image: lineItem.imageUrl,\n url: item.link,\n shareText: item.text,\n sharingLink: item.link,\n channelName: item.channel,\n channelCode: item.code,\n };\n\n return socialData;\n }, {} as InternalSocialDataList);\n}\n","import InternalShippingOption from './internal-shipping-option';\nimport ShippingOption from './shipping-option';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalShippingOption(\n option: ShippingOption,\n isSelected: boolean,\n): InternalShippingOption {\n return {\n description: option.description,\n module: option.type,\n price: option.cost,\n id: option.id,\n selected: isSelected,\n isRecommended: option.isRecommended,\n imageUrl: option.imageUrl,\n transitTime: option.transitTime,\n };\n}\n","import { pick } from 'lodash';\n\nimport { Address, mapToInternalAddress } from '../address';\nimport { mapToInternalCart } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { CheckoutButtonMethodType } from '../checkout-buttons/strategies';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { mapToInternalCustomer } from '../customer';\nimport { HostedFormOrderData } from '../hosted-form';\nimport {\n CardExpiryFormatter,\n CardNumberFormatter,\n HostedInputValues,\n} from '../hosted-form/iframe-content';\nimport { mapToInternalOrder } from '../order';\nimport { mapToInternalShippingOption } from '../shipping';\n\nimport isVaultedInstrument, { isFormattedVaultedInstrument } from './is-vaulted-instrument';\nimport Payment, {\n HostedCreditCardInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n} from './payment';\nimport PaymentMethod from './payment-method';\nimport PaymentRequestBody from './payment-request-body';\n\nexport default class PaymentRequestTransformer {\n private _cardExpiryFormatter = new CardExpiryFormatter();\n private _cardNumberFormatter = new CardNumberFormatter();\n\n transform(payment: Payment, checkoutState: InternalCheckoutSelectors): PaymentRequestBody {\n const billingAddress = checkoutState.billingAddress.getBillingAddress();\n const checkout = checkoutState.checkout.getCheckout();\n const customer = checkoutState.customer.getCustomer();\n const order = checkoutState.order.getOrder();\n const paymentMethod = checkoutState.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n const shippingAddress = this._mapShippingAddress(checkoutState, paymentMethod);\n const consignments = checkoutState.consignments.getConsignments();\n const shippingOption = checkoutState.consignments.getShippingOption();\n const storeConfig = checkoutState.config.getStoreConfig();\n const contextConfig = checkoutState.config.getContextConfig();\n const instrumentMeta = checkoutState.instruments.getInstrumentsMeta();\n const paymentMeta = checkoutState.paymentMethods.getPaymentMethodsMeta();\n const orderMeta = checkoutState.order.getOrderMeta();\n const internalCustomer =\n customer && billingAddress && mapToInternalCustomer(customer, billingAddress);\n\n const authToken =\n instrumentMeta &&\n payment.paymentData &&\n (isVaultedInstrument(payment.paymentData) ||\n isFormattedVaultedInstrument(payment.paymentData))\n ? `${checkoutState.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : checkoutState.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction: payment.additionalAction,\n authToken,\n customer: internalCustomer,\n billingAddress: billingAddress && mapToInternalAddress(billingAddress),\n shippingAddress: shippingAddress && mapToInternalAddress(shippingAddress, consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: payment.paymentData,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n quoteMeta: {\n request: {\n ...paymentMeta,\n geoCountryCode: contextConfig && contextConfig.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store: pick(storeConfig && storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n transformWithHostedFormData(\n values: HostedInputValues,\n data: HostedFormOrderData,\n nonce: string,\n ): PaymentRequestBody {\n const {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment = {},\n paymentMethod,\n paymentMethodMeta,\n } = data;\n const consignment = checkout && checkout.consignments[0];\n const shippingAddress = consignment && consignment.shippingAddress;\n const shippingOption = consignment && consignment.selectedShippingOption;\n\n return {\n additionalAction,\n authToken,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n customer:\n order &&\n order.billingAddress &&\n checkout &&\n mapToInternalCustomer(checkout.customer, order.billingAddress),\n billingAddress:\n order && order.billingAddress && mapToInternalAddress(order.billingAddress),\n shippingAddress:\n shippingAddress &&\n checkout &&\n mapToInternalAddress(shippingAddress, checkout.consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: this._transformHostedInputValues(values, payment, nonce),\n quoteMeta: {\n request: {\n ...paymentMethodMeta,\n geoCountryCode: config && config.context.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store:\n config &&\n pick(config.storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n private _transformPaymentMethod(paymentMethod: PaymentMethod): PaymentMethod {\n if (paymentMethod.method === 'multi-option' && !paymentMethod.gateway) {\n return { ...paymentMethod, gateway: paymentMethod.id };\n }\n\n if (paymentMethod.initializationData && paymentMethod.initializationData.gateway) {\n return { ...paymentMethod, id: paymentMethod.initializationData.gateway };\n }\n\n if (paymentMethod.id === CheckoutButtonMethodType.BRAINTREE_VENMO) {\n return { ...paymentMethod, id: CheckoutButtonMethodType.BRAINTREE_PAYPAL };\n }\n\n return paymentMethod;\n }\n\n private _transformHostedInputValues(\n values: HostedInputValues,\n payment: HostedCreditCardInstrument | HostedVaultedInstrument,\n nonce: string,\n ): PaymentInstrument {\n return 'instrumentId' in payment\n ? {\n ...payment,\n ccCvv: values.cardCodeVerification,\n ccNumber:\n values.cardNumberVerification &&\n this._cardNumberFormatter.unformat(values.cardNumberVerification),\n hostedFormNonce: nonce,\n }\n : {\n ...payment,\n ccCvv: values.cardCode,\n ccExpiry: this._cardExpiryFormatter.toObject(values.cardExpiry || ''),\n ccName: values.cardName || '',\n ccNumber: this._cardNumberFormatter.unformat(values.cardNumber || ''),\n hostedFormNonce: nonce,\n };\n }\n\n private _mapShippingAddress(\n checkoutState: InternalCheckoutSelectors,\n paymentMethod?: PaymentMethod,\n ): Address | undefined {\n if (paymentMethod) {\n const isBopisEnabled = paymentMethod.initializationData?.bopis?.enabled;\n const requiredAddress = paymentMethod.initializationData?.bopis?.requiredAddress;\n const consignments = checkoutState.consignments.getConsignments();\n const isPickup = consignments?.every((consignment) => consignment.selectedPickupOption);\n\n if (isBopisEnabled && isPickup && requiredAddress === 'none') {\n return undefined;\n }\n }\n\n return checkoutState.shippingAddress.getShippingAddress();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum PaymentProviderCustomerType {\n UpdatePaymentProviderCustomer = 'UPDATE_PAYMENT_PROVIDER_CUSTOMER',\n}\n\nexport type PaymentProviderCustomerAction = UpdatePaymentProviderCustomerAction;\n\nexport interface UpdatePaymentProviderCustomerAction extends Action {\n type: PaymentProviderCustomerType.UpdatePaymentProviderCustomer;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { Observable, of } from 'rxjs';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport {\n PaymentProviderCustomerAction,\n PaymentProviderCustomerType,\n} from './payment-provider-customer-actions';\n\nexport default class PaymentProviderCustomerActionCreator {\n updatePaymentProviderCustomer(\n providerCustomerData: PaymentProviderCustomer,\n ): Observable {\n return of(\n createAction(\n PaymentProviderCustomerType.UpdatePaymentProviderCustomer,\n providerCustomerData,\n ),\n );\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderPaymentsAction } from '../order';\n\nexport enum PaymentStrategyActionType {\n ExecuteFailed = 'PAYMENT_STRATEGY_EXECUTE_FAILED',\n ExecuteRequested = 'PAYMENT_STRATEGY_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'PAYMENT_STRATEGY_EXECUTE_SUCCEEDED',\n FinalizeFailed = 'PAYMENT_STRATEGY_FINALIZE_FAILED',\n FinalizeRequested = 'PAYMENT_STRATEGY_FINALIZE_REQUESTED',\n FinalizeSucceeded = 'PAYMENT_STRATEGY_FINALIZE_SUCCEEDED',\n InitializeFailed = 'PAYMENT_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'PAYMENT_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'PAYMENT_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type PaymentStrategyAction =\n | PaymentStrategyExecuteAction\n | PaymentStrategyFinalizeAction\n | PaymentStrategyInitializeAction\n | PaymentStrategyDeinitializeAction\n | PaymentStrategyWidgetAction;\n\nexport type PaymentStrategyExecuteAction =\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyFinalizeAction =\n | FinalizeRequestedAction\n | FinalizeSucceededAction\n | FinalizeFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type PaymentStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type PaymentStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface ExecuteRequestedAction extends Action {\n type: PaymentStrategyActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action {\n type: PaymentStrategyActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: PaymentStrategyActionType.ExecuteFailed;\n}\n\nexport interface FinalizeRequestedAction extends Action {\n type: PaymentStrategyActionType.FinalizeRequested;\n}\n\nexport interface FinalizeSucceededAction extends Action {\n type: PaymentStrategyActionType.FinalizeSucceeded;\n}\n\nexport interface FinalizeFailedAction extends Action {\n type: PaymentStrategyActionType.FinalizeFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: PaymentStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\n\nimport { PaymentRequestOptions } from './payment-request-options';\nimport { PaymentStrategyActionType, PaymentStrategyWidgetAction } from './payment-strategy-actions';\n\nexport default class PaymentStrategyWidgetActionCreator {\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n return concat(\n of(createAction(PaymentStrategyActionType.WidgetInteractionStarted, undefined, meta)),\n defer(() =>\n method().then(() =>\n createAction(\n PaymentStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.WidgetInteractionFailed, error, meta),\n ),\n );\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { AmazonPayRemoteCheckout } from './methods';\n\nexport enum RemoteCheckoutActionType {\n ForgetCheckoutRemoteCustomerRequested = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED',\n ForgetCheckoutRemoteCustomerSucceeded = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED',\n ForgetCheckoutRemoteCustomerFailed = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED',\n\n InitializeRemoteBillingRequested = 'INITIALIZE_REMOTE_BILLING_REQUESTED',\n InitializeRemoteBillingSucceeded = 'INITIALIZE_REMOTE_BILLING_SUCCEEDED',\n InitializeRemoteBillingFailed = 'INITIALIZE_REMOTE_BILLING_FAILED',\n\n InitializeRemoteShippingRequested = 'INITIALIZE_REMOTE_SHIPPING_REQUESTED',\n InitializeRemoteShippingSucceeded = 'INITIALIZE_REMOTE_SHIPPING_SUCCEEDED',\n InitializeRemoteShippingFailed = 'INITIALIZE_REMOTE_SHIPPING_FAILED',\n\n InitializeRemotePaymentRequested = 'INITIALIZE_REMOTE_PAYMENT_REQUESTED',\n InitializeRemotePaymentSucceeded = 'INITIALIZE_REMOTE_PAYMENT_SUCCEEDED',\n InitializeRemotePaymentFailed = 'INITIALIZE_REMOTE_PAYMENT_FAILED',\n\n LoadRemoteSettingsRequested = 'LOAD_REMOTE_SETTINGS_REQUESTED',\n LoadRemoteSettingsSucceeded = 'LOAD_REMOTE_SETTINGS_SUCCEEDED',\n LoadRemoteSettingsFailed = 'LOAD_REMOTE_SETTINGS_FAILED',\n\n SignOutRemoteCustomerRequested = 'SIGN_OUT_REMOTE_CUSTOMER_REQUESTED',\n SignOutRemoteCustomerSucceeded = 'SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED',\n SignOutRemoteCustomerFailed = 'SIGN_OUT_REMOTE_CUSTOMER_FAILED',\n\n UpdateRemoteCheckout = 'UPDATE_REMOTE_CHECKOUT',\n}\n\nexport type RemoteCheckoutAction =\n | ForgetCheckoutRemoteCustomerAction\n | InitializeRemoteBillingAction\n | InitializeRemoteShippingAction\n | InitializeRemotePaymentAction\n | SignOutRemoteCustomerAction\n | LoadRemoteSettingsAction\n | UpdateRemoteCheckoutAction;\n\nexport type ForgetCheckoutRemoteCustomerAction =\n | ForgetCheckoutRemoteCustomerRequestedAction\n | ForgetCheckoutRemoteCustomerSucceededAction\n | ForgetCheckoutRemoteCustomerFailedAction;\n\nexport interface ForgetCheckoutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested;\n}\n\nexport interface ForgetCheckoutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded;\n}\n\nexport interface ForgetCheckoutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed;\n}\n\nexport type InitializeRemoteBillingAction =\n | InitializeRemoteBillingSucceededAction\n | InitializeRemoteBillingFailedAction\n | InitializeRemoteBillingRequestedAction;\n\nexport interface InitializeRemoteBillingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingSucceeded;\n}\n\nexport interface InitializeRemoteBillingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingFailed;\n}\n\nexport interface InitializeRemoteBillingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingRequested;\n}\n\nexport type InitializeRemoteShippingAction =\n | InitializeRemoteShippingSucceededAction\n | InitializeRemoteShippingFailedAction\n | InitializeRemoteShippingRequestedAction;\n\nexport interface InitializeRemoteShippingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingSucceeded;\n}\n\nexport interface InitializeRemoteShippingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingFailed;\n}\n\nexport interface InitializeRemoteShippingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingRequested;\n}\n\nexport type InitializeRemotePaymentAction =\n | InitializeRemotePaymentSucceededAction\n | InitializeRemotePaymentFailedAction\n | InitializeRemotePaymentRequestedAction;\n\nexport interface InitializeRemotePaymentSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentSucceeded;\n}\n\nexport interface InitializeRemotePaymentFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentFailed;\n}\n\nexport interface InitializeRemotePaymentRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentRequested;\n}\n\nexport type SignOutRemoteCustomerAction =\n | SignOutRemoteCustomerSucceededAction\n | SignOutRemoteCustomerFailedAction\n | SignOutRemoteCustomerRequestedAction;\n\nexport interface SignOutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded;\n}\n\nexport interface SignOutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerFailed;\n}\n\nexport interface SignOutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerRequested;\n}\n\nexport type LoadRemoteSettingsAction =\n | LoadRemoteSettingsSucceededAction\n | LoadRemoteSettingsRequestedAction\n | LoadRemoteSettingsFailedAction;\n\nexport interface LoadRemoteSettingsSucceededAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsSucceeded;\n}\n\nexport interface LoadRemoteSettingsRequestedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsRequested;\n}\n\nexport interface LoadRemoteSettingsFailedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsFailed;\n}\n\nexport interface UpdateRemoteCheckoutAction extends Action {\n type: RemoteCheckoutActionType.UpdateRemoteCheckout;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutActionCreator } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutRequestSender, {\n InitializePaymentOptions,\n} from './remote-checkout-request-sender';\nimport { RemoteCheckoutStateData } from './remote-checkout-state';\n\n/**\n * @todo Convert this file into TypeScript properly\n * i.e.: Action\n */\nexport default class RemoteCheckoutActionCreator {\n constructor(\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n ) {}\n\n initializeBilling(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemoteBillingRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializeBilling(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteBillingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteBillingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializeShipping(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingRequested,\n undefined,\n { methodId },\n ),\n );\n\n this._remoteCheckoutRequestSender\n .initializeShipping(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteShippingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemotePaymentRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializePayment(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemotePaymentSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemotePaymentFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n loadSettings(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .loadSettings(methodId, options)\n .then(({ body }) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsSucceeded, body, {\n methodId,\n }),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.LoadRemoteSettingsFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n signOut(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.SignOutRemoteCustomerRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .signOut(methodId, options)\n .then(() => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n forgetCheckout(methodId: string, options?: RequestOptions): Observable {\n return concat(\n of(\n createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested,\n undefined,\n { methodId },\n ),\n ),\n defer(async () => {\n await this._remoteCheckoutRequestSender.forgetCheckout(options);\n await this._checkoutActionCreator.loadCurrentCheckout();\n\n return createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed,\n error,\n { methodId },\n ),\n ),\n );\n }\n\n updateCheckout(\n methodId: K,\n data: Partial,\n ): Action {\n return createAction(RemoteCheckoutActionType.UpdateRemoteCheckout, data, { methodId });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class RemoteCheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n initializeBilling(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/billing`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializeShipping(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/shipping`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializePayment(\n methodName: string,\n params?: InitializePaymentOptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/payment`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n loadSettings(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/settings`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n signOut(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/signout`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n generateToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/remote-checkout-token';\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n trackAuthorizationEvent({ timeout }: RequestOptions = {}): Promise> {\n const url =\n '/remote-checkout/events/shopper-checkout-service-provider-authorization-requested';\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n forgetCheckout({ timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/forget-checkout`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n\nexport interface InitializePaymentOptions {\n authorizationToken?: string;\n customerMessage?: string;\n referenceId?: string;\n useStoreCredit?: boolean;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nimport { ConsignmentMeta } from './consignment';\n\nexport enum ConsignmentActionType {\n CreateConsignmentsRequested = 'CREATE_CONSIGNMENTS_REQUESTED',\n CreateConsignmentsSucceeded = 'CREATE_CONSIGNMENTS_SUCCEEDED',\n CreateConsignmentsFailed = 'CREATE_CONSIGNMENTS_FAILED',\n\n UpdateConsignmentRequested = 'UPDATE_CONSIGNMENT_REQUESTED',\n UpdateConsignmentSucceeded = 'UPDATE_CONSIGNMENT_SUCCEEDED',\n UpdateConsignmentFailed = 'UPDATE_CONSIGNMENT_FAILED',\n\n DeleteConsignmentRequested = 'DELETE_CONSIGNMENT_REQUESTED',\n DeleteConsignmentSucceeded = 'DELETE_CONSIGNMENT_SUCCEEDED',\n DeleteConsignmentFailed = 'DELETE_CONSIGNMENT_FAILED',\n\n UpdateShippingOptionRequested = 'UPDATE_SHIPPING_OPTION_REQUESTED',\n UpdateShippingOptionSucceeded = 'UPDATE_SHIPPING_OPTION_SUCCEEDED',\n UpdateShippingOptionFailed = 'UPDATE_SHIPPING_OPTION_FAILED',\n\n LoadShippingOptionsRequested = 'LOAD_SHIPPING_OPTIONS_REQUESTED',\n LoadShippingOptionsSucceeded = 'LOAD_SHIPPING_OPTIONS_SUCCEEDED',\n LoadShippingOptionsFailed = 'LOAD_SHIPPING_OPTIONS_FAILED',\n}\n\nexport type ConsignmentAction =\n | CreateConsignmentsAction\n | UpdateConsignmentAction\n | DeleteConsignmentAction\n | UpdateShippingOptionAction\n | LoadShippingOptionsAction;\n\nexport type CreateConsignmentsAction =\n | CreateConsignmentsRequestedAction\n | CreateConsignmentsSucceededAction\n | CreateConsignmentsFailedAction;\n\nexport type UpdateConsignmentAction =\n | UpdateConsignmentRequestedAction\n | UpdateConsignmentSucceededAction\n | UpdateConsignmentFailedAction;\n\nexport type DeleteConsignmentAction =\n | DeleteConsignmentRequestedAction\n | DeleteConsignmentSucceededAction\n | DeleteConsignmentFailedAction;\n\nexport type UpdateShippingOptionAction =\n | UpdateShippingOptionRequestedAction\n | UpdateShippingOptionSucceededAction\n | UpdateShippingOptionFailedAction;\n\nexport type LoadShippingOptionsAction =\n | LoadShippingOptionsRequestedAction\n | LoadShippingOptionsSucceededAction\n | LoadShippingOptionsFailedAction;\n\nexport interface CreateConsignmentsRequestedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsRequested;\n}\n\nexport interface CreateConsignmentsSucceededAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsSucceeded;\n}\n\nexport interface CreateConsignmentsFailedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsFailed;\n}\n\nexport interface UpdateConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentRequested;\n}\n\nexport interface UpdateConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentSucceeded;\n}\n\nexport interface UpdateConsignmentFailedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentFailed;\n}\n\nexport interface DeleteConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentRequested;\n}\n\nexport interface DeleteConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentSucceeded;\n}\n\nexport interface DeleteConsignmentFailedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentFailed;\n}\n\nexport interface UpdateShippingOptionRequestedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionRequested;\n}\n\nexport interface UpdateShippingOptionSucceededAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionSucceeded;\n}\n\nexport interface UpdateShippingOptionFailedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionFailed;\n}\n\nexport interface LoadShippingOptionsRequestedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsRequested;\n}\n\nexport interface LoadShippingOptionsSucceededAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsSucceeded;\n}\n\nexport interface LoadShippingOptionsFailedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { find } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { Cart } from '../cart';\nimport {\n CheckoutIncludes,\n CheckoutParams,\n CheckoutRequestSender,\n InternalCheckoutSelectors,\n ReadableCheckoutStore,\n} from '../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport Consignment, {\n ConsignmentAssignmentBaseRequestBodyWithAddress,\n ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ConsignmentAssignmentRequestBody,\n ConsignmentCreateRequestBody,\n ConsignmentLineItem,\n ConsignmentRequestBody,\n ConsignmentShippingOptionRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n} from './consignment';\nimport {\n ConsignmentActionType,\n CreateConsignmentsAction,\n DeleteConsignmentAction,\n LoadShippingOptionsAction,\n UpdateConsignmentAction,\n UpdateShippingOptionAction,\n} from './consignment-actions';\nimport ConsignmentRequestSender from './consignment-request-sender';\n\nexport default class ConsignmentActionCreator {\n constructor(\n private _consignmentRequestSender: ConsignmentRequestSender,\n private _checkoutRequestSender: CheckoutRequestSender,\n ) {}\n\n unassignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n if (!existingConsignment) {\n throw new InvalidArgumentError('No consignment found for the specified address');\n }\n\n const lineItems = this._removeLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n );\n\n if (!lineItems.length) {\n return this.deleteConsignment(existingConsignment.id, options)(store);\n }\n\n return this.updateConsignment(\n {\n id: existingConsignment.id,\n address,\n lineItems,\n },\n options,\n )(store);\n };\n }\n\n assignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n return this._createOrUpdateConsignment(\n {\n id: existingConsignment && existingConsignment.id,\n address,\n lineItems: this._addLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n ),\n },\n options,\n )(store);\n };\n }\n\n selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const consignments = state.consignments.getConsignments();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!consignments || !consignments.length) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentUpdateBody = {\n id: consignments[0].id,\n shippingOptionId: id,\n };\n\n const consignmentMeta = {\n id: consignments[0].id,\n };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignmentUpdateBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n loadShippingOptions(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.LoadShippingOptionsRequested));\n\n this._checkoutRequestSender\n .loadCheckout(checkout.id, {\n ...options,\n params: {\n include: [CheckoutIncludes.AvailableShippingOptions],\n },\n })\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.LoadShippingOptionsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.LoadShippingOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const consignment = this._getUpdateAddressRequestBody(address, store);\n const consignments = store.getState().consignments.getConsignments();\n\n if (consignments && consignments.length) {\n (consignment as ConsignmentUpdateRequestBody).id = consignments[0].id;\n }\n\n return this._createOrUpdateConsignment(consignment, options)(store);\n };\n }\n\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.CreateConsignmentsRequested));\n\n this._consignmentRequestSender\n .createConsignments(checkout.id, consignments, options)\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.CreateConsignmentsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.CreateConsignmentsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n const consignmentMeta = { id: consignmentId };\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .deleteConsignment(checkout.id, consignmentId, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.DeleteConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n updateShippingOption(\n consignment: ConsignmentShippingOptionRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n private _createOrUpdateConsignment(\n consignment: ConsignmentCreateRequestBody | ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (this._isUpdateConsignmentRequest(consignment)) {\n return this.updateConsignment(consignment, options)(store);\n }\n\n return this.createConsignments([consignment], options)(store);\n };\n }\n\n private _getUpdateAddressRequestBody(\n address: AddressRequestBody,\n store: ReadableCheckoutStore,\n ): ConsignmentRequestBody {\n const state = store.getState();\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { physicalItems, customItems = [] } = cart.lineItems;\n\n return {\n address,\n lineItems: [...physicalItems, ...customItems].map((item) => ({\n itemId: item.id,\n quantity: item.quantity,\n })),\n };\n }\n\n private _removeLineItems(\n lineItems: ConsignmentLineItem[],\n consignment: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return this._hydrateLineItems(consignment.lineItemIds, cart)\n .map((existingItem) => {\n const sharedItem = find(\n lineItems,\n (lineItem) => lineItem.itemId === existingItem.itemId,\n );\n\n return {\n ...existingItem,\n quantity: sharedItem\n ? existingItem.quantity - sharedItem.quantity\n : existingItem.quantity,\n };\n })\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _addLineItems(\n lineItems: ConsignmentLineItem[],\n consignment?: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!consignment) {\n return lineItems;\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return lineItems\n .concat(this._hydrateLineItems(consignment.lineItemIds, cart))\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _hydrateLineItems(lineItemIds: string[], cart: Cart): ConsignmentLineItem[] {\n return lineItemIds.map((itemId) => {\n const item = find(cart.lineItems.physicalItems, (lineItem) => lineItem.id === itemId);\n\n return {\n itemId,\n quantity: item ? item.quantity : 0,\n };\n });\n }\n\n private _isUpdateConsignmentRequest(\n request: ConsignmentRequestBody,\n ): request is ConsignmentUpdateRequestBody {\n const updateRequest = request as ConsignmentUpdateRequestBody;\n\n return !!updateRequest.id;\n }\n\n private _consignmentHasAddress(\n consignment:\n | ConsignmentAssignmentBaseRequestBodyWithAddress\n | ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ): consignment is ConsignmentAssignmentBaseRequestBodyWithAddress {\n return typeof consignment === 'object' && 'address' in consignment;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutParams } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { ConsignmentsRequestBody, ConsignmentUpdateRequestBody } from './consignment';\n\nconst DEFAULT_INCLUDES = [\n 'consignments.availableShippingOptions',\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n];\n\nexport default class ConsignmentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createConsignments(\n checkoutId: string,\n consignments: ConsignmentsRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n updateConsignment(\n checkoutId: string,\n consignment: ConsignmentUpdateRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = consignment;\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n deleteConsignment(\n checkoutId: string,\n consignmentId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${consignmentId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = joinIncludes(DEFAULT_INCLUDES);\n\n return this._requestSender.delete(url, { params: { include }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Country } from '../geography';\n\nexport enum ShippingCountryActionType {\n LoadShippingCountriesRequested = 'LOAD_SHIPPING_COUNTRIES_REQUESTED',\n LoadShippingCountriesSucceeded = 'LOAD_SHIPPING_COUNTRIES_SUCCEEDED',\n LoadShippingCountriesFailed = 'LOAD_SHIPPING_COUNTRIES_FAILED',\n}\n\nexport type LoadShippingCountriesAction =\n | LoadShippingCountriesRequestedAction\n | LoadShippingCountriesSucceededAction\n | LoadShippingCountriesFailedAction;\n\nexport interface LoadShippingCountriesRequestedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesRequested;\n}\n\nexport interface LoadShippingCountriesSucceededAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesSucceeded;\n}\n\nexport interface LoadShippingCountriesFailedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport CheckoutStore from '../checkout/checkout-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryRequestSender from './shipping-country-request-sender';\n\nexport default class ShippingCountryActionCreator {\n constructor(\n private _shippingCountryRequestSender: ShippingCountryRequestSender,\n private _store: CheckoutStore,\n ) {}\n\n loadCountries(options?: RequestOptions): Observable {\n const { checkout } = this._store.getState();\n const checkoutData = checkout.getCheckout();\n\n const channelId = checkoutData ? checkoutData.channelId : null;\n\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesRequested));\n\n this._shippingCountryRequestSender\n .loadCountries(channelId, options)\n .then((response) => {\n observer.next(\n createAction(\n ShippingCountryActionType.LoadShippingCountriesSucceeded,\n response.body.data,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ShippingCountryActionType.LoadShippingCountriesFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { CountryResponseBody } from '../geography';\n\nexport default class ShippingCountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries(\n channelId: number | null,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const channelIdParam = channelId ? `?channel_id=${channelId}` : '';\n const url = `/internalapi/v1/shipping/countries${channelIdParam}`;\n\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum SpamProtectionActionType {\n InitializeFailed = 'SPAM_PROTECTION_INITIALIZE_FAILED',\n InitializeSucceeded = 'SPAM_PROTECTION_INITIALIZE_SUCCEEDED',\n InitializeRequested = 'SPAM_PROTECTION_INITIALIZE_REQUESTED',\n VerifyCheckoutRequested = 'SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED',\n VerifyCheckoutSucceeded = 'SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED',\n VerifyCheckoutFailed = 'SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED',\n ExecuteRequested = 'SPAM_PROTECTION_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'SPAM_PROTECTION_EXECUTE_SUCCEEDED',\n ExecuteFailed = 'SPAM_PROTECTION_EXECUTE_FAILED',\n}\n\nexport type SpamProtectionAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | CheckoutVerifyRequestedAction\n | CheckoutVerifyFailedAction\n | CheckoutVerifySucceededAction;\n\nexport interface InitializeRequestedAction extends Action {\n type: SpamProtectionActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: SpamProtectionActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: SpamProtectionActionType.InitializeFailed;\n}\n\nexport interface ExecuteRequestedAction extends Action {\n type: SpamProtectionActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action<{ token: string }> {\n type: SpamProtectionActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: SpamProtectionActionType.ExecuteFailed;\n}\n\nexport interface CheckoutVerifyRequestedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutRequested;\n}\n\nexport interface CheckoutVerifyFailedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutFailed;\n}\n\nexport interface CheckoutVerifySucceededAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutSucceeded;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of } from 'rxjs';\nimport { catchError, switchMap, take } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\nimport isSpamProtectionExecuteSucceededAction from './is-spam-protection-succeeded-action';\nimport { SpamProtectionAction, SpamProtectionActionType } from './spam-protection-actions';\nimport { SpamProtectionOptions } from './spam-protection-options';\nimport SpamProtectionRequestSender from './spam-protection-request-sender';\n\nexport default class SpamProtectionActionCreator {\n constructor(\n private _googleRecaptcha: GoogleRecaptcha,\n private _requestSender: SpamProtectionRequestSender,\n ) {}\n\n initialize(\n options?: SpamProtectionOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n if (!options && !document.getElementById(spamProtectionElementId)) {\n const spamProtectionElement = document.createElement('div');\n\n spamProtectionElement.setAttribute('id', spamProtectionElementId);\n document.body.appendChild(spamProtectionElement);\n }\n\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const recaptchaSitekey = storeConfig.checkoutSettings.googleRecaptchaSitekey;\n\n await this._googleRecaptcha.load(spamProtectionElementId, recaptchaSitekey);\n\n return createAction(SpamProtectionActionType.InitializeSucceeded);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.InitializeFailed, error),\n ),\n );\n }\n\n verifyCheckoutSpamProtection(): ThunkAction {\n return (store) =>\n defer(() => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return concat(\n of(createAction(SpamProtectionActionType.VerifyCheckoutRequested)),\n from(this.execute()(store)).pipe(\n switchMap((action) => {\n if (\n !isSpamProtectionExecuteSucceededAction(action) ||\n !action.payload\n ) {\n return of(action);\n }\n\n return from(\n this._requestSender.validate(checkout.id, action.payload.token),\n ).pipe(\n switchMap(({ body }) =>\n concat(\n of(action),\n of(\n createAction(\n SpamProtectionActionType.VerifyCheckoutSucceeded,\n body,\n ),\n ),\n ),\n ),\n );\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.VerifyCheckoutFailed, error),\n ),\n );\n });\n }\n\n execute(): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.ExecuteRequested)),\n this.initialize()(store),\n this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw error;\n }\n\n if (error || !token) {\n throw new SpamProtectionFailedError();\n }\n\n return createAction(SpamProtectionActionType.ExecuteSucceeded, {\n token,\n });\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.ExecuteFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class SpamProtectionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n validate(\n checkoutId: string,\n token: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/spam-protection`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: { token }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum StoreCreditActionType {\n ApplyStoreCreditRequested = 'APPLY_STORE_CREDIT_REQUESTED',\n ApplyStoreCreditSucceeded = 'APPLY_STORE_CREDIT_SUCCEEDED',\n ApplyStoreCreditFailed = 'APPLY_STORE_CREDIT_FAILED',\n}\n\nexport type StoreCreditAction = ApplyStoreCreditAction;\n\nexport type ApplyStoreCreditAction =\n | ApplyStoreCreditRequestedAction\n | ApplyStoreCreditSucceededAction\n | ApplyStoreCreditFailedAction;\n\nexport interface ApplyStoreCreditRequestedAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditRequested;\n}\n\nexport interface ApplyStoreCreditSucceededAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditSucceeded;\n}\n\nexport interface ApplyStoreCreditFailedAction\n extends Action> {\n type: StoreCreditActionType.ApplyStoreCreditFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditRequestSender from './store-credit-request-sender';\n\nexport default class StoreCreditActionCreator {\n constructor(private _storeCreditRequestSender: StoreCreditRequestSender) {}\n\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(StoreCreditActionType.ApplyStoreCreditRequested)),\n defer(async () => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(checkout.id, options)\n : this._storeCreditRequestSender.removeStoreCredit(checkout.id, options));\n\n return createAction(StoreCreditActionType.ApplyStoreCreditSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(StoreCreditActionType.ApplyStoreCreditFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class StoreCreditRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Subscriptions } from './subscriptions';\n\nexport enum SubscriptionsActionType {\n UpdateSubscriptionsRequested = 'UPDATE_SUBSCRIPTIONS_REQUESTED',\n UpdateSubscriptionsSucceeded = 'UPDATE_SUBSCRIPTIONS_SUCCEEDED',\n UpdateSubscriptionsFailed = 'UPDATE_SUBSCRIPTIONS_FAILED',\n}\nexport type UpdateSubscriptionsAction =\n | UpdateSubscriptionsRequestedAction\n | UpdateSubscriptionsSucceededAction\n | UpdateSubscriptionsFailedAction;\n\nexport interface UpdateSubscriptionsRequestedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsRequested;\n}\n\nexport interface UpdateSubscriptionsSucceededAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsSucceeded;\n}\n\nexport interface UpdateSubscriptionsFailedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsFailed;\n}\n","import { RequestError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the subscriptions fails to be updated\n */\nexport default class UpdateSubscriptionsError extends RequestError {\n constructor(response?: Response) {\n super(response);\n\n this.name = 'UpdateSubscriptionsError';\n this.type = 'update_subscriptions';\n }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n Subscriptions,\n SubscriptionsActionType,\n SubscriptionsRequestSender,\n UpdateSubscriptionsAction,\n} from '../subscription';\n\nimport { UpdateSubscriptionsError } from './errors';\n\nexport default class SubscriptionsActionCreator {\n constructor(private _subscriptionsRequestSender: SubscriptionsRequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SubscriptionsActionType.UpdateSubscriptionsRequested)),\n defer(async () => {\n const { body } = await this._subscriptionsRequestSender.updateSubscriptions(\n subscriptions,\n options,\n );\n\n return createAction(SubscriptionsActionType.UpdateSubscriptionsSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n SubscriptionsActionType.UpdateSubscriptionsFailed,\n new UpdateSubscriptionsError(error),\n ),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Subscriptions } from './subscriptions';\n\nexport default class SubscriptionsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/subscriptions';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: subscriptions, headers, timeout });\n }\n}\n","import { isPlainObject as lodashIsPlainObject } from 'lodash';\n\n// We need this wrapper because Lodash's version doesn't act as a type guard\nexport default function isPlainObject(value: any): value is object {\n return lodashIsPlainObject(value);\n}\n","import { memoize } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\n\nconst cloneDeep = memoize((input: T): T => {\n if (Array.isArray(input)) {\n // Fixed in later versions of typescript https://github.com/microsoft/TypeScript/issues/36390\n return (input as any[]).map((value: T[keyof T]) => cloneDeepSafe(value)) as any;\n }\n\n if (isPlainObject(input)) {\n return (Object.keys(input) as Array).reduce(\n (result, key) => ({\n ...result,\n [key]: cloneDeepSafe(input[key]),\n }),\n {},\n ) as T;\n }\n\n return input;\n});\n\n// Use WeakMap as the MapCache, this allows for better garbage collection\n// There's a deprecated `clear` method in the lodash implementation\n// of MapCache, hence the `any`\ncloneDeep.cache = new WeakMap() as any;\n\n/**\n * This is a wrapper function for `cloneDeep`. We need it because `cloneDeep` is\n * a memoized function using an instance of `WeakMap` as its cache. Without this\n * wrapper, the memoized function will throw an error if it is called with a\n * non-object argument.\n */\nconst cloneDeepSafe = (input: T): T => {\n return typeof input === 'object' && input !== null ? cloneDeep(input) : input;\n};\n\n/**\n * Clone the return value of a function. If the result is the same as previous\n * calls, return the previous clone instead of cloning it again.\n */\nexport default function cloneResult(fn: T): T {\n return ((...args: any[]) => cloneDeepSafe(fn(...args))) as T;\n}\n\nexport type Func = (...args: any[]) => any;\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { cloneResult as clone } from '../common/utility';\n\nexport default function createPaymentIntegrationSelectors({\n billingAddress: { getBillingAddress, getBillingAddressOrThrow },\n cart: { getCart, getCartOrThrow },\n checkout: { getCheckout, getCheckoutOrThrow, getOutstandingBalance },\n config: {\n getContextConfig,\n getHost,\n getLocale,\n getStoreConfig,\n getStoreConfigOrThrow,\n getConfig,\n },\n consignments: { getConsignments, getConsignmentsOrThrow },\n countries: { getCountries },\n customer: { getCustomer, getCustomerOrThrow },\n instruments: {\n getCardInstrument,\n getCardInstrumentOrThrow,\n getInstruments,\n getInstrumentsMeta,\n },\n order: { getOrder, getOrderOrThrow, getOrderMeta },\n payment: {\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n isPaymentDataRequired,\n },\n paymentMethods: { getPaymentMethod, getPaymentMethodOrThrow, getPaymentMethodsMeta },\n paymentProviderCustomer: { getPaymentProviderCustomer, getPaymentProviderCustomerOrThrow },\n paymentStrategies: { isInitialized: isPaymentMethodInitialized },\n shippingAddress: {\n getShippingAddress,\n getShippingAddressOrThrow,\n getShippingAddresses,\n getShippingAddressesOrThrow,\n },\n shippingCountries: { getShippingCountries },\n}: InternalCheckoutSelectors): PaymentIntegrationSelectors {\n return {\n getHost: clone(getHost),\n getLocale: clone(getLocale),\n getBillingAddress: clone(getBillingAddress),\n getBillingAddressOrThrow: clone(getBillingAddressOrThrow),\n getCart: clone(getCart),\n getCartOrThrow: clone(getCartOrThrow),\n getCheckout: clone(getCheckout),\n getCheckoutOrThrow: clone(getCheckoutOrThrow),\n getCountries: clone(getCountries),\n getStoreConfig: clone(getStoreConfig),\n getStoreConfigOrThrow: clone(getStoreConfigOrThrow),\n getConfig: clone(getConfig),\n getConsignments: clone(getConsignments),\n getConsignmentsOrThrow: clone(getConsignmentsOrThrow),\n getContextConfig: clone(getContextConfig),\n getCustomer: clone(getCustomer),\n getCustomerOrThrow: clone(getCustomerOrThrow),\n getCardInstrument: clone(getCardInstrument),\n getInstruments: clone(getInstruments),\n getCardInstrumentOrThrow: clone(getCardInstrumentOrThrow),\n getOrder: clone(getOrder),\n getOrderOrThrow: clone(getOrderOrThrow),\n getOrderMeta: clone(getOrderMeta),\n getInstrumentsMeta: clone(getInstrumentsMeta),\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n getPaymentMethod: clone(getPaymentMethod),\n getPaymentMethodOrThrow: clone(getPaymentMethodOrThrow),\n getPaymentMethodsMeta: clone(getPaymentMethodsMeta),\n getPaymentProviderCustomer: clone(getPaymentProviderCustomer),\n getPaymentProviderCustomerOrThrow: clone(getPaymentProviderCustomerOrThrow),\n getShippingAddress: clone(getShippingAddress),\n getShippingAddressOrThrow: clone(getShippingAddressOrThrow),\n getShippingAddresses: clone(getShippingAddresses),\n getShippingAddressesOrThrow: clone(getShippingAddressesOrThrow),\n getShippingCountries: clone(getShippingCountries),\n getOutstandingBalance: clone(getOutstandingBalance),\n isPaymentDataRequired,\n isPaymentMethodInitialized,\n };\n}\n","import {\n BillingAddressRequestBody,\n BuyNowCartRequestBody,\n Cart,\n HostedForm,\n HostedFormOptions,\n InitializeOffsitePaymentConfig,\n OrderRequestBody,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n RequestOptions,\n ShippingAddressRequestBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport { Checkout, CheckoutActionCreator, CheckoutStore, CheckoutValidator } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { CustomerActionCreator, CustomerCredentials } from '../customer';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport {\n PaymentProviderCustomer,\n PaymentProviderCustomerActionCreator,\n} from '../payment-provider-customer';\nimport PaymentActionCreator from '../payment/payment-action-creator';\nimport PaymentMethodActionCreator from '../payment/payment-method-action-creator';\nimport PaymentStrategyWidgetActionCreator from '../payment/payment-strategy-widget-action-creator';\nimport { RemoteCheckoutActionCreator } from '../remote-checkout';\nimport { InitializePaymentOptions } from '../remote-checkout/remote-checkout-request-sender';\nimport { ConsignmentActionCreator, ShippingCountryActionCreator } from '../shipping';\nimport { PaymentHumanVerificationHandler, SpamProtectionActionCreator } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\n\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default class DefaultPaymentIntegrationService implements PaymentIntegrationService {\n private _storeProjection: DataStoreProjection;\n\n constructor(\n private _store: CheckoutStore,\n private _storeProjectionFactory: PaymentIntegrationStoreProjectionFactory,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _checkoutValidator: CheckoutValidator,\n private _hostedFormFactory: HostedFormFactory,\n private _orderActionCreator: OrderActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n private _customerActionCreator: CustomerActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _paymentStrategyWidgetActionCreator: PaymentStrategyWidgetActionCreator,\n ) {\n this._storeProjection = this._storeProjectionFactory.create(this._store);\n }\n\n createHostedForm(host: string, options: HostedFormOptions): HostedForm {\n return this._hostedFormFactory.create(host, options);\n }\n\n subscribe(\n subscriber: (state: PaymentIntegrationSelectors) => void,\n ...filters: Array<(state: PaymentIntegrationSelectors) => unknown>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n getState(): PaymentIntegrationSelectors {\n return this._storeProjection.getState();\n }\n\n async initializeOffsitePayment(\n initializeOffsitePaymentConfig: InitializeOffsitePaymentConfig,\n ): Promise {\n await this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment(initializeOffsitePaymentConfig),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadCheckout(id?: string): Promise {\n if (id) {\n await this._store.dispatch(this._checkoutActionCreator.loadCheckout(id));\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout());\n }\n\n return this._storeProjection.getState();\n }\n\n async loadDefaultCheckout(): Promise {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethod(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethods(options?: RequestOptions): Promise {\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods(options));\n\n return this._storeProjection.getState();\n }\n\n async submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n return this._storeProjection.getState();\n }\n\n async submitPayment(payment: Payment): Promise {\n await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n\n return this._storeProjection.getState();\n }\n\n async finalizeOrder(options?: RequestOptions): Promise {\n const {\n order: { getOrderOrThrow },\n } = this._store.getState();\n\n await this._store.dispatch(\n this._orderActionCreator.finalizeOrder(getOrderOrThrow().orderId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async updateBillingAddress(\n payload: BillingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._billingAddressActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async updateShippingAddress(\n payload: ShippingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._consignmentActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(id, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signOutCustomer(options?: RequestOptions): Promise {\n await this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n\n return this._storeProjection.getState();\n }\n\n async createBuyNowCart(\n buyNowCartRequestBody: BuyNowCartRequestBody,\n options?: RequestOptions,\n ): Promise {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n buyNowCartRequestBody,\n options,\n );\n\n return buyNowCart;\n }\n\n async applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async verifyCheckoutSpamProtection(): Promise {\n const { checkout } = this._store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._store.dispatch(\n this._spamProtectionActionCreator.verifyCheckoutSpamProtection(),\n );\n }\n\n return this._storeProjection.getState();\n }\n\n async loadCurrentOrder(options?: RequestOptions): Promise {\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder(options));\n\n return this._storeProjection.getState();\n }\n\n async updatePaymentProviderCustomer(\n paymentProviderCustomer: PaymentProviderCustomer,\n ): Promise {\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer(\n paymentProviderCustomer,\n ),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadShippingCountries(options?: RequestOptions): Promise {\n await this._store.dispatch(this._shippingCountryActionCreator.loadCountries(options));\n\n return this._storeProjection.getState();\n }\n\n async deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.deleteConsignment(consignmentId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, params, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async forgetCheckout(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.forgetCheckout(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async remoteCheckoutSignOut(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._remoteCheckoutActionCreator.signOut(methodId, options));\n\n return this._storeProjection.getState();\n }\n\n async validateCheckout(checkout?: Checkout, options?: RequestOptions): Promise {\n await this._checkoutValidator.validate(checkout, options);\n }\n\n async handlePaymentHumanVerification(\n errorOrId: Error | string,\n key?: string,\n ): Promise {\n if (typeof errorOrId === 'string') {\n return this._paymentHumanVerificationHandler.handle(errorOrId, key ?? '');\n }\n\n return this._paymentHumanVerificationHandler.handle(errorOrId);\n }\n\n async widgetInteraction(\n callback: () => Promise,\n ): Promise {\n await this._store.dispatch(\n this._paymentStrategyWidgetActionCreator.widgetInteraction(callback),\n { queueId: 'widgetInteraction' },\n );\n\n return this._storeProjection.getState();\n }\n}\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\n\nexport default class PaymentIntegrationStoreProjectionFactory {\n constructor(\n private _transformSelectors: (\n selectors: InternalCheckoutSelectors,\n ) => PaymentIntegrationSelectors,\n ) {}\n\n create(store: ReadableCheckoutStore): DataStoreProjection {\n return createDataStoreProjection(store, this._transformSelectors);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { CustomerActionCreator, CustomerRequestSender } from '../customer';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n PaymentActionCreator,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentRequestSender,\n PaymentRequestTransformer,\n} from '../payment';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\nimport PaymentStrategyWidgetActionCreator from '../payment/payment-strategy-widget-action-creator';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n} from '../shipping';\nimport {\n createSpamProtection,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentIntegrationSelectors from './create-payment-integration-selectors';\nimport DefaultPaymentIntegrationService from './default-payment-integration-service';\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default function createPaymentIntegrationService(\n store: CheckoutStore,\n): PaymentIntegrationService {\n const {\n config: { getHost, getLocale },\n } = store.getState();\n\n const requestSender = createRequestSender({ host: getHost() });\n\n const storeProjectionFactory = new PaymentIntegrationStoreProjectionFactory(\n createPaymentIntegrationSelectors,\n );\n\n const checkoutActionCreator = new CheckoutActionCreator(\n new CheckoutRequestSender(requestSender),\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const checkoutValidator = new CheckoutValidator(new CheckoutRequestSender(requestSender));\n\n const hostedFormFactory = new HostedFormFactory(store);\n\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n new CheckoutValidator(new CheckoutRequestSender(requestSender)),\n );\n\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n\n const consignmentActionCreator = new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n );\n\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const paymentActionCreator = new PaymentActionCreator(\n new PaymentRequestSender(createPaymentClient(store)),\n orderActionCreator,\n new PaymentRequestTransformer(),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n new SpamProtectionActionCreator(\n createSpamProtection(createScriptLoader()),\n new SpamProtectionRequestSender(requestSender),\n ),\n );\n\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n\n const cartRequestSender = new CartRequestSender(requestSender);\n\n const paymentProviderCustomerActionCreator = new PaymentProviderCustomerActionCreator();\n\n const shippingCountryActionCreator = new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale: getLocale() }),\n store,\n );\n\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n new RemoteCheckoutRequestSender(requestSender),\n checkoutActionCreator,\n );\n\n const paymentStrategyWidgetActionCreator = new PaymentStrategyWidgetActionCreator();\n\n return new DefaultPaymentIntegrationService(\n store,\n storeProjectionFactory,\n checkoutActionCreator,\n checkoutValidator,\n hostedFormFactory,\n orderActionCreator,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n paymentActionCreator,\n paymentHumanVerificationHandler,\n customerActionCreator,\n cartRequestSender,\n storeCreditActionCreator,\n spamProtectionActionCreator,\n paymentProviderCustomerActionCreator,\n shippingCountryActionCreator,\n remoteCheckoutActionCreator,\n paymentStrategyWidgetActionCreator,\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","import {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeError,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeModule,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeScriptLoader,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n PAYPAL_COMPONENTS,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaypalHostWindow } from '../paypal';\n\nexport default class BraintreeSDKCreator {\n private _client?: Promise;\n private _3ds?: Promise;\n private _paypalCheckout?: Promise;\n private _clientToken?: string;\n private _visaCheckout?: Promise;\n private _venmoCheckout?: Promise;\n private _dataCollectors: {\n default?: Promise;\n paypal?: Promise;\n } = {};\n private _window: PaypalHostWindow;\n\n constructor(private _braintreeScriptLoader: BraintreeScriptLoader) {\n this._window = window;\n }\n\n initialize(clientToken: string) {\n this._clientToken = clientToken;\n }\n\n getClient(): Promise {\n if (!this._clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this._client) {\n this._client = this._braintreeScriptLoader\n .loadClient()\n .then((client) => client.create({ authorization: this._clientToken }));\n }\n\n return this._client;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this._braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n\n if (!this._window.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(\n this._getPayPalSDKConfig(config),\n paypalSdkLoadCallback,\n );\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this._paypalCheckout = paypalCheckout.create(paypalCheckoutConfig, paypalCheckoutCallback);\n\n return this._paypalCheckout;\n }\n\n async getVenmoCheckout(\n onSuccess: (braintreeVenmoCheckout: BraintreeVenmoCheckout) => void,\n onError: (error: BraintreeError | UnsupportedBrowserError) => void,\n ): Promise {\n if (!this._venmoCheckout) {\n const client = await this.getClient();\n\n const venmoCheckout = await this._braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const venmoCheckoutCallback = (\n error: BraintreeError,\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n ): void => {\n if (error) {\n return onError(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return onError(new UnsupportedBrowserError());\n }\n\n onSuccess(braintreeVenmoCheckout);\n };\n\n this._venmoCheckout = venmoCheckout.create(venmoCheckoutConfig, venmoCheckoutCallback);\n }\n\n return this._venmoCheckout;\n }\n\n get3DS(): Promise {\n if (!this._3ds) {\n this._3ds = Promise.all([this.getClient(), this._braintreeScriptLoader.load3DS()]).then(\n ([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }),\n );\n }\n\n return this._3ds;\n }\n\n getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options && options.paypal ? 'paypal' : 'default';\n let cached = this._dataCollectors[cacheKey];\n\n if (!cached) {\n cached = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadDataCollector(),\n ])\n .then(([client, dataCollector]) =>\n dataCollector.create({ client, kount: true, ...options }),\n )\n .catch((error) => {\n if (error && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n return { deviceData: undefined, teardown: () => Promise.resolve() };\n }\n\n throw error;\n });\n\n this._dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getVisaCheckout(): Promise {\n if (!this._visaCheckout) {\n this._visaCheckout = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, visaCheckout]) => visaCheckout.create({ client }));\n }\n\n return this._visaCheckout;\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const [client, hostedFields] = await Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadHostedFields(),\n ]);\n\n return hostedFields.create({ ...options, client });\n }\n\n teardown(): Promise {\n return Promise.all([\n this._teardown(this._3ds),\n this._teardown(this._dataCollectors.default),\n this._teardown(this._dataCollectors.paypal),\n this._teardown(this._paypalCheckout),\n this._teardown(this._venmoCheckout),\n this._teardown(this._visaCheckout),\n ]).then(() => {\n this._3ds = undefined;\n this._dataCollectors = {};\n this._paypalCheckout = undefined;\n this._venmoCheckout = undefined;\n this._visaCheckout = undefined;\n });\n }\n\n private _teardown(module?: Promise) {\n return module\n ? module\n .then((mod) => mod.teardown())\n .catch((error) => {\n if (error.code !== 'METHOD_CALLED_AFTER_TEARDOWN') {\n throw error;\n }\n })\n : Promise.resolve();\n }\n\n private _getPayPalSDKConfig(config: Partial) {\n return {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n commit: false,\n };\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { Address, LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nimport { BraintreeDataCollector } from './braintree';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport {\n VisaCheckoutAddress,\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\nexport default class BraintreeVisaCheckoutPaymentProcessor {\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(\n clientToken: string,\n options: VisaCheckoutInitializeOptions,\n ): Promise {\n this._braintreeSDKCreator.initialize(clientToken);\n\n return this._braintreeSDKCreator.getVisaCheckout().then((visaCheckout) =>\n visaCheckout.createInitOptions({\n settings: {\n locale: options.locale,\n shipping: {\n collectShipping: options.collectShipping,\n },\n },\n paymentRequest: {\n currencyCode: options.currencyCode,\n subtotal: String(options.subtotal),\n },\n }),\n );\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n handleSuccess(\n payment: VisaCheckoutPaymentSuccessPayload,\n shipping?: Address,\n billing?: Address,\n ): Promise {\n return this._braintreeSDKCreator.getVisaCheckout().then((braintreeVisaCheckout) =>\n Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this._braintreeSDKCreator.getDataCollector(),\n ]).then(([tokenizedPayload, dataCollector]) => {\n const {\n shippingAddress = this._toVisaCheckoutAddress(shipping),\n billingAddress = this._toVisaCheckoutAddress(billing),\n } = tokenizedPayload;\n\n return this._postForm(\n {\n ...tokenizedPayload,\n shippingAddress,\n billingAddress,\n },\n dataCollector,\n );\n }),\n );\n }\n\n private _postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: this._getCardInformation(cardInformation),\n billing_address: this._getAddress(userEmail, billingAddress),\n shipping_address: this._getAddress(userEmail, shippingAddress),\n },\n });\n }\n\n private _toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private _getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastTwo: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n };\n }\n}\n\nexport interface VisaCheckoutInitializeOptions {\n locale?: string;\n collectShipping?: boolean;\n subtotal?: number;\n currencyCode?: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\n\nexport default function createBraintreeVisaCheckoutPaymentProcessor(\n scriptLoader: ScriptLoader,\n requestSender: RequestSender,\n) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, window);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n\n return new BraintreeVisaCheckoutPaymentProcessor(braintreeSDKCreator, requestSender);\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { VisaCheckoutHostWindow, VisaCheckoutSDK } from './visacheckout';\n\nexport default class VisaCheckoutScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: VisaCheckoutHostWindow = window,\n ) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n )\n .then(() => {\n if (!this._window.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.V;\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Masterpass, MasterpassHostWindow } from './masterpass';\n\ninterface MasterpassScriptLoaderParams {\n useMasterpassSrc: boolean;\n language: string;\n testMode?: boolean;\n checkoutId?: string;\n}\n\nexport default class MasterpassScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n public _window: MasterpassHostWindow = window,\n ) {}\n\n async load({\n useMasterpassSrc,\n language,\n testMode,\n checkoutId,\n }: MasterpassScriptLoaderParams): Promise {\n if (useMasterpassSrc) {\n const subdomain = testMode ? 'sandbox.' : '';\n const params = [`locale=${language}`, `checkoutid=${checkoutId}`];\n\n const sourceUrl = [\n `https://${subdomain}src.mastercard.com/srci/integration/merchant.js`,\n params.join('&'),\n ].join('?');\n\n await this._scriptLoader.loadScript(sourceUrl);\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n\n await this._scriptLoader.loadScript(\n `//${testMode ? 'sandbox.' : ''}masterpass.com/integration/merchant.js`,\n );\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutScriptLoader,\n} from '../../../payment/strategies/braintree';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategyActionCreator from '../../customer-strategy-action-creator';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _buttonClassName = 'visa-checkout-wrapper';\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this._paymentMethod;\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { container, onError = () => {} } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: true,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n clientToken,\n initOptions,\n ),\n ])\n .then(([visaCheckout, initOptions]) => {\n const signInButton = this._createSignInButton(\n container,\n this._buttonClassName,\n );\n\n visaCheckout.init(initOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload).catch(\n (error) => onError(error),\n ),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n\n return signInButton;\n })\n .then((signInButton) => {\n signInButton.style.visibility = 'visible';\n });\n })\n .then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut('braintreevisacheckout', options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._customerStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(async () => {\n await this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n );\n this._onPaymentSelectComplete();\n });\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _onPaymentSelectComplete(): void {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n }\n\n private _createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return (\n (container.querySelector(`.${buttonClass}`) as HTMLElement) ||\n this._insertVisaCheckoutButton(container, buttonClass)\n );\n }\n\n private _insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class DefaultCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _customerActionCreator: CustomerActionCreator,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","export default function getCallbackUrl(origin: string): string {\n return `${window.location.origin}/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=${origin}`;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n es: ['es_es', 'es_mx', 'es_pe', 'es_co', 'es_ar', 'es_cl'],\n en: [\n 'en_us',\n 'en_gb',\n 'en_ca',\n 'en_es',\n 'en_fr',\n 'en_ie',\n 'en_sg',\n 'en_au',\n 'en_nz',\n 'en_my',\n 'en_hk',\n 'en_th',\n 'en_ae',\n 'en_sa',\n 'en_qa',\n 'en_kw',\n 'en_za',\n ],\n pt: ['pt_br'],\n zu: ['zu_za'],\n ar: ['ar_sa', 'ar_ae', 'ar_qa', 'ar_kw'],\n zh: ['zh_sg', 'zh_hk'],\n ms: ['ms_my'],\n uk: ['uk_ua'],\n sv: ['sv_se'],\n hr: ['hr_hr'],\n pl: ['pl_pl'],\n nl: ['nl_be'],\n it: ['it_it'],\n de: ['de_de'],\n fr: ['fr_fr', 'fr_ca'],\n};\n","import { supportedLocales } from './masterpass-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace('-', '_').toLowerCase().split('_');\n const formattedLocale = `${language}_${country}`;\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'en_us';\n }\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n formatLocale,\n getCallbackUrl,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class MasterpassCustomerStrategy implements CustomerStrategy {\n private _signInButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { masterpass: masterpassOptions, methodId } = options;\n\n if (!masterpassOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.masterpass\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { container } = masterpassOptions;\n\n const payload = {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: cart.cartAmount.toString(),\n currency: cart.currency.code,\n cartId: cart.id,\n suppressShippingAddress: false,\n callbackUrl: getCallbackUrl('checkout'),\n };\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((Masterpass) => {\n this._signInButton = this._createSignInButton(container);\n\n this._signInButton.addEventListener('click', () => {\n Masterpass.checkout(payload);\n });\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (this._paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = this._paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = this._paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n container.appendChild(button);\n\n return button;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotImplementedError } from '../../../common/error/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class SquareCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n ) {}\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Extension } from './extension';\n\nexport enum ExtensionActionType {\n LoadExtensionsRequested = 'LOAD_EXTENSIONS_REQUESTED',\n LoadExtensionsSucceeded = 'LOAD_EXTENSIONS_SUCCEEDED',\n LoadExtensionsFailed = 'LOAD_EXTENSIONS_FAILED',\n RenderExtensionRequested = 'RENDER_EXTENSION_REQUESTED',\n RenderExtensionSucceeded = 'RENDER_EXTENSION_SUCCEEDED',\n RenderExtensionFailed = 'RENDER_EXTENSION_FAILED',\n}\n\nexport type ExtensionAction =\n | LoadExtensionsRequestedAction\n | LoadExtensionsSucceededAction\n | LoadExtensionsFailedAction\n | RenderExtensionRequestedAction\n | RenderExtensionSucceededAction\n | RenderExtensionFailedAction;\n\nexport interface LoadExtensionsRequestedAction extends Action {\n type: ExtensionActionType.LoadExtensionsRequested;\n}\n\nexport interface LoadExtensionsSucceededAction extends Action {\n type: ExtensionActionType.LoadExtensionsSucceeded;\n}\n\nexport interface LoadExtensionsFailedAction extends Action {\n type: ExtensionActionType.LoadExtensionsFailed;\n}\n\nexport interface RenderExtensionRequestedAction extends Action {\n type: ExtensionActionType.RenderExtensionRequested;\n}\n\nexport interface RenderExtensionSucceededAction extends Action {\n type: ExtensionActionType.RenderExtensionSucceeded;\n}\n\nexport interface RenderExtensionFailedAction extends Action {\n type: ExtensionActionType.RenderExtensionFailed;\n}\n","export enum ExtensionInternalEventType {\n ExtensionReady = 'EXTENSION:READY',\n ExtensionFailed = 'EXTENSION:FAILED',\n}\n\nexport interface ExtensionReadyEvent {\n type: ExtensionInternalEventType.ExtensionReady;\n}\n\nexport interface ExtensionFailedEvent {\n type: ExtensionInternalEventType.ExtensionFailed;\n}\n\nexport type ExtensionInternalEvent = ExtensionReadyEvent | ExtensionFailedEvent;\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotFoundError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to no extension configured for this region.');\n\n this.name = 'ExtensionNotFoundError';\n this.type = 'extension_not_found';\n }\n}\n","import { IframeEventPoster } from '../common/iframe';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { Extension } from './extension';\n\nexport function createExtensionEventPoster(extension: Extension): IframeEventPoster {\n const iframe = document\n .querySelector(`[data-extension-id=\"${extension.id}\"]`)\n ?.querySelector('iframe');\n\n if (!iframe?.contentWindow) {\n throw new ExtensionNotFoundError(\n `Unable to post due to no extension rendered for ID: ${extension.id}.`,\n );\n }\n\n return new IframeEventPoster(extension.url, iframe.contentWindow);\n}\n","import { IFrameComponent, IFrameOptions } from 'iframe-resizer';\n\nexport {\n HeightCalculationMethod,\n IFrameComponent,\n IFrameMessageData,\n IFrameObject,\n IFrameOptions,\n IFramePage,\n IFramePageOptions,\n IFrameResizedData,\n IFrameScrollData,\n PageInfo,\n WidthCalculationMethod,\n} from 'iframe-resizer';\n\n// The reason why we are wrapping the original `iframeResizer` function imported\n// from the package is because the package sets up event listeners (window\n// resize etc...) as soon as the package is imported. Therefore, to defer the\n// side effect from happening until the function is actually being used, we are\n// importing the package inside this function. To minimise the chance of\n// importing the original package inadvertently, we are also re-exporting all of\n// its public interfaces. The re-exports do not cause any side effect because\n// they are plain TypeScript interfaces; meaning they are only used for type\n// checks rather than for code output.\nexport function iframeResizer(\n options: IFrameOptions,\n target: string | HTMLElement,\n): IFrameComponent[] {\n /* eslint-disable @typescript-eslint/no-var-requires */\n const { iframeResizer: originalIframeResizer } = require('iframe-resizer');\n\n return originalIframeResizer(options, target);\n}\n\n// We also need to wrap the original `iframeResizer.contentWindow` because\n// similarly the package sets up event listeners as soon as the package gets\n// imported. Another reason is that if it is imported at the top level using a\n// regular import statement, it will be stripped out by Webpack as it is\n// considered as \"unused\", unless we explicitly mark it as a package that\n// produces side effects.\nexport function setupContentWindowForIframeResizer(): void {\n require('iframe-resizer/js/iframeResizer.contentWindow');\n}\n","import { ExtensionEventType } from './extension-events';\n\nexport enum ExtensionInternalCommandType {\n Subscribe = 'EXTENSION_INTERNAL:SUBSCRIBE',\n Unsubscribe = 'EXTENSION_INTERNAL:UNSUBSCRIBE',\n ResizeIframe = 'EXTENSION_INTERNAL:RESIZE_IFRAME',\n}\n\nexport interface ExtensionSubscribeCommand {\n type: ExtensionInternalCommandType.Subscribe;\n payload: {\n extensionId: string;\n eventType: ExtensionEventType;\n };\n}\n\nexport interface ExtensionUnsubscribeCommand {\n type: ExtensionInternalCommandType.Unsubscribe;\n payload: {\n extensionId: string;\n eventType: ExtensionEventType;\n };\n}\n\nexport interface ExtensionResizeIframeCommand {\n type: ExtensionInternalCommandType.ResizeIframe;\n payload: {\n extensionId: string;\n };\n}\n\nexport interface ExtensionInternalCommandMap {\n [ExtensionInternalCommandType.Subscribe]: ExtensionSubscribeCommand;\n [ExtensionInternalCommandType.Unsubscribe]: ExtensionUnsubscribeCommand;\n [ExtensionInternalCommandType.ResizeIframe]: ExtensionResizeIframeCommand;\n}\n\nexport type ExtensionInternalCommand =\n | ExtensionSubscribeCommand\n | ExtensionUnsubscribeCommand\n | ExtensionResizeIframeCommand;\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotLoadedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to load an extension');\n\n this.name = 'ExtensionNotLoadedError';\n this.type = 'extension_not_loaded';\n }\n}\n","import { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { parseUrl } from '../common/url';\n\nimport { ExtensionNotLoadedError } from './errors';\nimport { ExtensionInternalCommandType } from './extension-internal-commands';\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(\n src: string,\n containerId: string,\n initCallback: () => void,\n failedCallback: () => void,\n ): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new ExtensionNotLoadedError(\n 'Unable to embed the iframe because the container element could not be found.',\n );\n }\n\n const iframe = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout, initCallback, failedCallback).catch(\n (error) => {\n container.removeChild(iframe);\n\n throw error;\n },\n );\n }\n\n private async _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n initCallback: () => void,\n failedCallback: () => void,\n ): Promise {\n const detachmentObserver = new DetachmentObserver(new MutationObserverFactory());\n\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n const promise = new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n try {\n failedCallback();\n } catch (error) {\n if (error instanceof Error) {\n // eslint-disable-next-line no-console\n console.error(\n `Extension rendering timed out after ${timeoutInterval}ms, and the callback function could not be executed. Error: ${error.message}`,\n );\n }\n }\n\n reject(\n new ExtensionNotLoadedError(\n 'Unable to load the extension because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== parseUrl(iframe.src).origin) {\n return;\n }\n\n if (isIframeEvent(event.data, ExtensionInternalCommandType.ResizeIframe)) {\n iframe.style.display = '';\n\n const iframes = iframeResizer(\n {\n autoResize: false,\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: 'bodyOffset',\n initCallback,\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n\n return detachmentObserver.ensurePresence([iframe], promise);\n }\n}\n","export type ExtensionCommand =\n | ReloadCheckoutCommand\n | ShowLoadingIndicatorCommand\n | SetIframeStyleCommand;\n\nexport enum ExtensionCommandType {\n ReloadCheckout = 'EXTENSION:RELOAD_CHECKOUT',\n ShowLoadingIndicator = 'EXTENSION:SHOW_LOADING_INDICATOR',\n SetIframeStyle = 'EXTENSION:SET_IFRAME_STYLE',\n}\n\nexport interface ExtensionCommandContext {\n extensionId: string;\n}\n\nexport interface ReloadCheckoutCommand {\n type: ExtensionCommandType.ReloadCheckout;\n}\n\nexport interface ShowLoadingIndicatorCommand {\n type: ExtensionCommandType.ShowLoadingIndicator;\n payload: {\n show: boolean;\n };\n}\n\nexport interface SetIframeStyleCommand {\n type: ExtensionCommandType.SetIframeStyle;\n payload: {\n style: {\n [key: string]: string | number | null;\n };\n };\n}\n\nexport interface ExtensionCommandMap {\n [ExtensionCommandType.ReloadCheckout]: ReloadCheckoutCommand;\n [ExtensionCommandType.ShowLoadingIndicator]: ShowLoadingIndicatorCommand;\n [ExtensionCommandType.SetIframeStyle]: SetIframeStyleCommand;\n}\n","import { createExtensionEventPoster } from './create-extension-event-poster';\nimport { Extension, ExtensionIframeConfig } from './extension';\nimport { ExtensionInternalEvent, ExtensionInternalEventType } from './extension-internal-events';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport class ExtensionIframe {\n private _iframe: HTMLIFrameElement | undefined;\n private _url: URL;\n\n constructor(\n private _containerId: string,\n private _extension: Extension,\n private _config: ExtensionIframeConfig,\n ) {\n const { cartId, parentOrigin } = this._config;\n\n this._url = new URL(this._extension.url);\n\n this._url.searchParams.set('extensionId', this._extension.id);\n this._url.searchParams.set('cartId', cartId);\n this._url.searchParams.set('parentOrigin', parentOrigin);\n }\n\n async attach(): Promise {\n if (\n document\n .querySelector(`[data-extension-id=\"${this._extension.id}\"]`)\n ?.querySelector('iframe')\n ) {\n return;\n }\n\n const iframeCreator = new ResizableIframeCreator();\n const iframeResizerCallback = (type: ExtensionInternalEventType) => {\n const poster = createExtensionEventPoster(this._extension);\n\n poster.post({\n type,\n });\n };\n const initCallback = () => {\n iframeResizerCallback(ExtensionInternalEventType.ExtensionReady);\n };\n const failedCallback = () => {\n iframeResizerCallback(ExtensionInternalEventType.ExtensionFailed);\n };\n\n this._iframe = await iframeCreator.createFrame(\n this._url.toString(),\n this._containerId,\n initCallback,\n failedCallback,\n );\n\n const container = document.getElementById(this._containerId);\n\n container?.setAttribute('data-extension-id', this._extension.id);\n }\n\n detach(): void {\n if (this._iframe && this._iframe.parentElement) {\n this._iframe.parentElement.removeChild(this._iframe);\n }\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { RequestOptions } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\n\nexport class ExtensionActionCreator {\n constructor(private _requestSender: ExtensionRequestSender) {}\n\n loadExtensions(\n options?: RequestOptions,\n ): ThunkAction {\n return () =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(ExtensionActionType.LoadExtensionsRequested));\n\n this._requestSender\n .loadExtensions(options)\n .then((response) => {\n const extensions = response.body;\n\n observer.next(\n createAction(ExtensionActionType.LoadExtensionsSucceeded, extensions),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(ExtensionActionType.LoadExtensionsFailed, response),\n );\n });\n });\n }\n\n renderExtension(\n container: string,\n region: ExtensionRegion,\n ): ThunkAction {\n return (store) =>\n Observable.create(async (observer: Observer) => {\n const state = store.getState();\n const { id: cartId } = state.cart.getCartOrThrow();\n const {\n links: { checkoutLink },\n checkoutSettings: { features },\n } = state.config.getStoreConfigOrThrow();\n\n if (!features['PROJECT-5029.checkout_extension']) {\n return observer.complete();\n }\n\n const extension = state.extensions.getExtensionByRegion(region);\n\n try {\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension configured for the region: ${region}.`,\n );\n }\n\n observer.next(createAction(ExtensionActionType.RenderExtensionRequested));\n\n const iframe = new ExtensionIframe(container, extension, {\n cartId,\n parentOrigin: parseUrl(checkoutLink).origin,\n });\n\n await iframe.attach();\n\n observer.next(createAction(ExtensionActionType.RenderExtensionSucceeded));\n observer.complete();\n } catch (error) {\n observer.error(\n createErrorAction(ExtensionActionType.RenderExtensionFailed, error),\n );\n }\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Extension } from './extension';\n\nexport const EXTENSIONS_API_URL = '/api/storefront/checkout-extensions';\n\nexport class ExtensionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadExtensions({ timeout, params }: RequestOptions = {}): Promise> {\n return this._requestSender.get(EXTENSIONS_API_URL, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class UnsupportedExtensionCommandError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to unsupported extension command.');\n\n this.name = 'UnsupportedExtensionCommandError';\n this.type = 'unsupported_extension_command_error';\n }\n}\n","import { ReadableCheckoutStore } from '../checkout';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\n\nimport { createExtensionEventPoster } from './create-extension-event-poster';\nimport { ExtensionNotFoundError } from './errors';\nimport { UnsupportedExtensionCommandError } from './errors/unsupported-extension-command-error';\nimport { Extension } from './extension';\nimport {\n ExtensionCommandContext,\n ExtensionCommandMap,\n ExtensionCommandType,\n} from './extension-commands';\nimport { ExtensionEvent } from './extension-events';\n\nexport class ExtensionMessenger {\n private _extensions: Extension[] | undefined;\n\n constructor(\n private _store: ReadableCheckoutStore,\n private _listeners: {\n [extensionId: string]: IframeEventListener;\n } = {},\n private _posters: { [extensionId: string]: IframeEventPoster } = {},\n ) {}\n\n listen(\n extensionId: string,\n command: T,\n commandHandler: (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandContext,\n ) => void,\n ): () => void {\n const extension = this._getExtensionById(extensionId);\n\n if (!this._listeners[extensionId]) {\n this._listeners[extensionId] = new IframeEventListener(extension.url);\n }\n\n const listener = this._listeners[extensionId];\n\n listener.listen();\n\n const validCommandType = this._validateCommand(command);\n\n const commandHandlerProxy = (\n command: ExtensionCommandMap[T],\n context?: ExtensionCommandContext,\n ) => {\n if (context?.extensionId === extensionId) {\n commandHandler(command, context);\n }\n };\n\n listener.addListener(validCommandType, commandHandlerProxy);\n\n return () => {\n listener.removeListener(validCommandType, commandHandlerProxy);\n };\n }\n\n stopListen(extensionId: string): void {\n if (!this._listeners[extensionId]) {\n return;\n }\n\n const listener = this._listeners[extensionId];\n\n listener.stopListen();\n }\n\n post(extensionId: string, event: ExtensionEvent): void {\n if (!this._posters[extensionId]) {\n const extension = this._getExtensionById(extensionId);\n\n this._posters[extensionId] = createExtensionEventPoster(extension);\n }\n\n this._posters[extensionId].post(event);\n }\n\n private _getExtensionById(extensionId: string): Extension {\n const {\n extensions: { getExtensions },\n } = this._store.getState();\n\n this._extensions = getExtensions();\n\n if (!this._extensions) {\n throw new ExtensionNotFoundError(`Extension configurations not found.`);\n }\n\n const extension = this._extensions.find((e) => e.id === extensionId);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension found for ID: ${extensionId}.`,\n );\n }\n\n return extension;\n }\n\n private _validateCommand(command: T): T {\n if (Object.values(ExtensionCommandType).includes(command)) {\n return command;\n }\n\n throw new UnsupportedExtensionCommandError();\n }\n}\n","import { Consignment } from '../shipping';\n\nexport enum ExtensionEventType {\n ConsignmentsChanged = 'EXTENSION:CONSIGNMENTS_CHANGED',\n}\n\nexport interface ConsignmentsChangedEvent {\n type: ExtensionEventType.ConsignmentsChanged;\n payload: {\n consignments: Consignment[];\n previousConsignments: Consignment[];\n };\n}\n\nexport type ExtensionEvent = ConsignmentsChangedEvent;\n\nexport interface ExtensionEventMap {\n [ExtensionEventType.ConsignmentsChanged]: ConsignmentsChangedEvent;\n}\n","import { CheckoutSelectors } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { IframeEventListener } from '../common/iframe';\n\nimport { ExtensionEvent, ExtensionEventType } from './extension-events';\nimport {\n ExtensionInternalCommandMap,\n ExtensionInternalCommandType,\n ExtensionSubscribeCommand,\n ExtensionUnsubscribeCommand,\n} from './extension-internal-commands';\nimport { ExtensionMessenger } from './extension-messenger';\nimport { ExtensionChangeSubscriber, ExtensionChangeUnsubscriber } from './subscribers';\n\nexport class ExtensionEventBroadcaster {\n private _subscribed: { [id: string]: boolean } = {};\n private _unsubscribers: { [type: string]: ExtensionChangeUnsubscriber } = {};\n private _listeners: { [id: string]: IframeEventListener } = {};\n\n constructor(\n private _store: DataStoreProjection,\n private _extensionMessenger: ExtensionMessenger,\n private _subscribers: Record,\n ) {}\n\n listen(): void {\n const {\n data: { getExtensions },\n } = this._store.getState();\n\n getExtensions()?.forEach((extension) => {\n if (this._listeners[extension.id]) {\n return;\n }\n\n const eventListener = new IframeEventListener(\n extension.url,\n );\n\n eventListener.addListener(\n ExtensionInternalCommandType.Subscribe,\n this._handleSubscribe.bind(this),\n );\n\n eventListener.addListener(\n ExtensionInternalCommandType.Unsubscribe,\n this._handleUnsubscribe.bind(this),\n );\n\n eventListener.listen();\n\n this._listeners[extension.id] = eventListener;\n });\n }\n\n broadcast(event: ExtensionEvent): void {\n const {\n data: { getExtensions },\n } = this._store.getState();\n\n getExtensions()?.forEach((extension) => {\n if (!this._subscribed[extension.id]) {\n return;\n }\n\n this._extensionMessenger.post(extension.id, event);\n });\n }\n\n private _handleSubscribe({\n payload: { eventType, extensionId },\n }: ExtensionSubscribeCommand): void {\n this._subscribed[extensionId] = true;\n\n if (this._unsubscribers[eventType]) {\n return;\n }\n\n this._unsubscribers[eventType] = this._subscribers[eventType](this._store, this);\n }\n\n private _handleUnsubscribe({\n payload: { eventType, extensionId },\n }: ExtensionUnsubscribeCommand): void {\n delete this._subscribed[extensionId];\n\n if (Object.keys(this._subscribed).length) {\n return;\n }\n\n this._unsubscribers[eventType]?.();\n\n delete this._unsubscribers[eventType];\n }\n}\n","import { CheckoutSelectors } from '../../checkout';\nimport { DataStoreProjection } from '../../common/data-store';\nimport { ExtensionEventBroadcaster } from '../extension-event-broadcaster';\nimport { ExtensionEventType } from '../extension-events';\n\nimport { ExtensionChangeSubscriber } from './extension-change-subscriber';\n\nexport const subscribeConsignmentsChange: ExtensionChangeSubscriber = (\n store: DataStoreProjection,\n broadcaster: ExtensionEventBroadcaster,\n) => {\n const {\n data: { getConsignments: getInitialConsignments },\n } = store.getState();\n\n let consignments = getInitialConsignments() ?? [];\n\n return store.subscribe(\n ({ data: { getConsignments } }) => {\n const currentConsignments = getConsignments() ?? [];\n\n if (currentConsignments === consignments) {\n return;\n }\n\n broadcaster.broadcast({\n type: ExtensionEventType.ConsignmentsChanged,\n payload: {\n consignments: currentConsignments,\n previousConsignments: consignments,\n },\n });\n\n consignments = currentConsignments;\n },\n ({ data: { getConsignments } }) => getConsignments(),\n );\n};\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenV2HostWindow } from '../types';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenV2HostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-8ofgICZZ/k5cC5N7xegqFZOA73H9RQ7H13439JfAZW8Gj3qjuKL2isaTD3GMIhDE',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-wG2z9zSQo61EIvyXmiFCo+zB3y0ZB4hsrXVcANmpP8HLthjoQJQPBh7tZKJSV8jA',\n crossorigin: 'anonymous',\n },\n },\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","export enum AdyenV3ActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2 = 'threeDS2',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n\n /*\n * The Component displays the widget which the shopper uses to complete the payment.\n * */\n Sdk = 'sdk',\n}\n\nexport enum AdyenV2ActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2Challenge = 'threeDS2Challenge',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface BoletoDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n shopperName?: {\n firstName?: string;\n lastName?: string;\n };\n socialSecurityNumber?: string;\n}\n\ninterface CardPaymentMethodState extends AdyenPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenV2Action {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenV2ActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenV3Action {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenV3ActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport type AdyenAction = AdyenV2Action | AdyenV3Action;\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n\n /**\n * A callback that gets called when an action, for example a QR code or 3D Secure 2 authentication screen, is shown to the shopper\n */\n onActionHandled?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n\n showBrandsUnderCardNumber?: boolean;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenComponentEventState, component: AdyenComponent): void;\n\n /**\n * Called when the shopper selects the Pay button and payment details are valid.\n */\n onSubmit?(state: AdyenComponentEventState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenV2Action | AdyenV3Action,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | AdyenV3ThreeDS2ChallengeComponentOptions\n | AdyenV2ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: AdyenComponentState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n submit(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * Configuration for specific payment methods.\n */\n paymentMethodsConfiguration?: {\n klarna: {\n useKlarnaWidget: boolean;\n };\n klarna_account: {\n useKlarnaWidget: boolean;\n };\n klarna_paynow: {\n useKlarnaWidget: boolean;\n };\n card?: {\n installmentOptions?: {\n card?: {\n values: number[];\n plans?: string[];\n };\n visa?: {\n values: number[];\n plans?: string[];\n };\n mc?: {\n values: number[];\n plans?: string[];\n };\n diners?: {\n values: number[];\n plans?: string[];\n };\n jcb?: {\n values: number[];\n plans?: string[];\n };\n showInstallmentAmounts?: boolean;\n };\n };\n };\n\n showPayButton?: boolean;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: AdyenComponentEventState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: AdyenComponentEventState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n firstName?: string;\n lastName?: string;\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenCreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\ntype AdyenClientConstructor = (configuration: AdyenConfiguration) => Promise;\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\nexport interface AdyenV3HostWindow extends Window {\n AdyenCheckout?: AdyenClientConstructor;\n}\n\nexport interface AdyenV2HostWindow extends Window {\n AdyenCheckout?: new (configuration: AdyenConfiguration) => AdyenClient;\n}\n\nexport interface AdyenIdealComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenBoletoComponentOptions extends AdyenComponentEvents {\n personalDetailsRequired?: boolean;\n billingAddressRequired?: boolean;\n showEmailAddress?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface AdyenThreeDS2Options extends AdyenAdditionalActionCallbacks {\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVV2/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface IdealStateData {\n issuer: string;\n}\n\ninterface SepaStateData {\n ownerName: string;\n ibanNumber: string;\n}\n\ninterface CardStateData {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenComponentState {\n data?: CardStateData | IdealStateData | SepaStateData;\n issuer?: string;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n installments?: { value: number; plan?: 'string' };\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface BoletoState {\n data: BoletoDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface AdyenV3ThreeDS2ChallengeComponentOptions {\n challengeWindowSize?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenV2ThreeDS2ChallengeComponentOptions {\n size?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ActionHandledReturnObject {\n componentType: string;\n actionDescription: string;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onActionHandled?(rtnObj: ActionHandledReturnObject): void;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenValidationState {\n valid: boolean;\n fieldType?: AdyenCardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenCardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenComponentEventState = CardState | BoletoState | WechatState;\n\nexport type AdyenComponentOptions =\n | AdyenCreditCardComponentOptions\n | AdyenIdealComponentOptions\n | AdyenBoletoComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport interface AdyenV3PaymentMethodInitializationData {\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n installmentOptions?: null | {\n card?: {\n values: number[];\n plans?: string[];\n };\n visa?: {\n values: number[];\n plans?: string[];\n };\n mc?: {\n values: number[];\n plans?: string[];\n };\n diners?: {\n values: number[];\n plans?: string[];\n };\n jcb?: {\n values: number[];\n plans?: string[];\n };\n };\n}\n\nexport interface AdyenV2PaymentMethodInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { AdyenComponentEventState, CardState } from '../types';\n\nexport default function isCardState(param: AdyenComponentEventState): param is CardState {\n return (\n (typeof param === 'object' &&\n typeof (param as CardState).data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof (param as CardState).data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrumentPayload,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrumentPayload,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import StandardError from './standard-error';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { some } from 'lodash';\n\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentEventState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV2ActionType,\n AdyenV2PaymentInitializeOptions,\n AdyenV2PaymentMethodInitializationData,\n AdyenV2ScriptLoader,\n CardStateErrors,\n isAccountState,\n isCardState,\n WithAdyenV2PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n BillingAddress,\n getBrowserInfo,\n HostedInstrument,\n InvalidArgumentError,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class AdyenV2PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentEventState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV2PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV2PaymentInitializeOptions,\n ): Promise {\n const { adyenv2 } = options;\n\n if (!adyenv2) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv2\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv2;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { originKey, clientKey, environment, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = clientKey || '';\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n const shouldSaveInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument;\n\n if (!payment) {\n return Promise.reject(new PaymentArgumentInvalidError(['payment']));\n }\n\n this._validateCardData();\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState;\n\n if (!componentState) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n if (isCardState(componentState) || isAccountState(componentState)) {\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument:\n shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV2PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv2\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _getThreeDS2ChallengeWidgetSize(): string {\n const { additionalActionOptions, threeDS2Options } = this._getPaymentInitializeOptions();\n const widgetSize = additionalActionOptions.widgetSize || threeDS2Options?.widgetSize;\n\n if (!widgetSize) {\n return '05';\n }\n\n return widgetSize;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { threeDS2ContainerId, additionalActionOptions } =\n this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete } = additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n size: this._getThreeDS2ChallengeWidgetSize(),\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenV2ActionType.ThreeDS2Challenge ||\n adyenAction.type === AdyenV2ActionType.QRCode,\n );\n }\n\n additionalActionComponent.mount(`#${containerId || threeDS2ContainerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv2.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv2.options,\n styles: {\n ...adyenv2.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv2.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv2.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv2.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv2.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n switch (paymentMethod.method) {\n case AdyenPaymentMethodType.CreditCard:\n case AdyenPaymentMethodType.ACH:\n case AdyenPaymentMethodType.Bancontact: {\n const billingAddress = this._paymentIntegrationService\n .getState()\n .getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) => this._updateComponentState(componentState),\n data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n break;\n }\n\n case AdyenPaymentMethodType.IDEAL:\n case AdyenPaymentMethodType.SEPA:\n if (!adyenv2.hasVaultedInstruments) {\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) =>\n this._updateComponentState(componentState),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n ),\n );\n }\n } else {\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n break;\n\n case AdyenPaymentMethodType.AliPay:\n case AdyenPaymentMethodType.GiroPay:\n case AdyenPaymentMethodType.Sofort:\n case AdyenPaymentMethodType.Klarna:\n case AdyenPaymentMethodType.KlarnaPayNow:\n case AdyenPaymentMethodType.KlarnaAccount:\n case AdyenPaymentMethodType.Vipps:\n case AdyenPaymentMethodType.WeChatPayQR:\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _updateComponentState(componentState: AdyenComponentEventState) {\n this._componentState = componentState;\n }\n\n private _validateCardData(): void {\n const adyenv2 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv2.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n const isEmptyString = (value: string) => value.toString().trim().length === 0;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n /**\n * For some reason adyen sdk doesn't return isValid for payment methods with select field in form(iDeal for example)\n * so we need to check state issuer field\n */\n if (\n Object.keys(cardComponent.state).length === 0 ||\n (!cardComponent.state.isValid && !cardComponent.state.issuer) ||\n // prevent empty sepa fields from being sent\n (cardComponent.props?.type === 'sepadirectdebit' &&\n cardComponent.state.data &&\n Object.values(cardComponent.state.data).some(isEmptyString))\n ) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { AccountState, AdyenComponentEventState } from '../types';\n\nexport default function isAccountState(param: AdyenComponentEventState): param is AccountState {\n const bankSupported = ['ideal', 'sepadirectdebit', 'directEbanking', 'giropay'];\n\n return bankSupported.indexOf((param as AccountState).data.paymentMethod.type) !== -1;\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV2ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV2PaymentStrategy from './adyenv2-payment-strategy';\n\nconst createAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV2PaymentStrategy(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV2PaymentStrategy, [{ gateway: 'adyenv2' }]);\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenV3HostWindow } from '../types';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenV3HostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.58.0/adyen.css`,\n {\n prepend: false,\n attributes: {\n integrity:\n 'sha384-zgFNrGzbwuX5qJLys75cOUIGru/BoEzhGMyC07I3OSdHqXuhUfoDPVG03G+61oF4',\n crossorigin: 'anonymous',\n },\n },\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.58.0/adyen.js`,\n {\n async: true,\n attributes: {\n integrity:\n 'sha384-e0EBlzLdOXxOJimp2uut2z1m98HS2cdhQw+OmeJDp7MRCPRNrQhjIWZiWiIscJvf',\n crossorigin: 'anonymous',\n },\n },\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentEventState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV3ActionType,\n AdyenV3PaymentInitializeOptions,\n AdyenV3PaymentMethodInitializationData,\n AdyenV3ScriptLoader,\n CardStateErrors,\n isBoletoState,\n isCardState,\n WithAdyenV3PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n BillingAddress,\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class Adyenv3PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentEventState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV3PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV3PaymentInitializeOptions,\n ): Promise {\n const { adyenv3 } = options;\n\n if (!adyenv3) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv3\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv3;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { environment, clientKey, paymentMethodsResponse, installmentOptions } =\n paymentMethod.initializationData || {};\n\n this._adyenClient = await this._scriptLoader.load({\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: true,\n },\n klarna_account: {\n useKlarnaWidget: true,\n },\n klarna_paynow: {\n useKlarnaWidget: true,\n },\n ...(installmentOptions\n ? {\n card: {\n installmentOptions: {\n showInstallmentAmounts: true,\n ...installmentOptions,\n },\n },\n }\n : {}),\n },\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n clientKey,\n paymentMethodsResponse,\n showPayButton: false,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n this._validateCardData();\n\n if (\n payment.methodId === 'klarna' ||\n payment.methodId === 'klarna_account' ||\n payment.methodId === 'klarna_paynow'\n ) {\n this._paymentComponent?.submit();\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState || {\n data: { paymentMethod: { type: payment.methodId } },\n };\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n\n let paymentToken = JSON.stringify({\n ...componentState.data.paymentMethod,\n type: payment.methodId,\n origin: window.location.origin,\n });\n\n if (payment.methodId === 'boletobancario' && isBoletoState(componentState)) {\n paymentToken = JSON.stringify({\n socialSecurityNumber: componentState.data.socialSecurityNumber,\n ...componentState.data.shopperName,\n type: payment.methodId,\n origin: window.location.origin,\n });\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: paymentToken,\n },\n ...(isCardState(componentState) && componentState.data.installments\n ? {\n installments: {\n value: componentState.data.installments.value,\n plan: componentState.data.installments.plan || 'regular',\n },\n }\n : {}),\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _updateComponentState(componentState: AdyenComponentEventState) {\n this._componentState = componentState;\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV3PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv3\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { additionalActionOptions } = this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete, widgetSize, onActionHandled } =\n additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onActionHandled: (additionalActionState) => {\n if (\n onActionHandled &&\n typeof onActionHandled === 'function' &&\n additionalActionState.componentType !== '3DS2Fingerprint'\n ) {\n onActionHandled();\n }\n },\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n challengeWindowSize: widgetSize || '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad && typeof onBeforeLoad === 'function') {\n onBeforeLoad(\n adyenAction.type === AdyenV3ActionType.ThreeDS2 ||\n adyenAction.type === AdyenV3ActionType.QRCode ||\n adyenAction.type === AdyenV3ActionType.Sdk,\n );\n }\n\n this._mountElement(additionalActionComponent, containerId);\n\n if (onLoad && typeof onLoad === 'function') {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n firstName: prefillCardHolderName ? firstName : '',\n lastName: prefillCardHolderName ? lastName : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv3.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv3.options,\n styles: {\n ...adyenv3.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv3.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv3.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv3.validateCardFields(validateState),\n });\n\n try {\n this._mountElement(\n cardVerificationComponent,\n adyenv3.cardVerificationContainerId,\n );\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n const billingAddress = this._paymentIntegrationService.getState().getBillingAddress();\n\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv3.options,\n showBrandsUnderCardNumber: false,\n billingAddressRequired: false,\n showEmailAddress: false,\n onChange: (componentState) => this._updateComponentState(componentState),\n onSubmit: (componentState) => this._updateComponentState(componentState),\n ...(billingAddress\n ? { data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName) }\n : {}),\n });\n\n try {\n this._mountElement(paymentComponent, adyenv3.containerId);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _validateCardData(): void {\n const adyenv3 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv3.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n if (Object.keys(cardComponent.state).length === 0 || !cardComponent.state.isValid) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n private _mountElement(adyenComponent: AdyenComponent, containerId: string): void {\n if (!document.getElementById(containerId)) {\n return;\n }\n\n adyenComponent.mount(`#${containerId}`);\n }\n}\n","import { AdyenComponentEventState, BoletoState } from '../types';\n\nexport default function isBoletoState(param: AdyenComponentEventState): param is BoletoState {\n return (\n (typeof param === 'object' && typeof (param as BoletoState).data.socialSecurityNumber) ===\n 'string' &&\n typeof (param as BoletoState).data.shopperName?.firstName === 'string' &&\n typeof (param as BoletoState).data.shopperName?.lastName === 'string'\n );\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV3ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV3PaymentStrategy from './adyenv3-payment-strategy';\n\nconst createAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV3PaymentStrategy(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV3PaymentStrategy, [{ gateway: 'adyenv3' }]);\n","import {\n AmountTransformer,\n Consignment,\n itemsRequireShipping,\n LineItemCategory,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Order,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n Affirm,\n AffirmAddress,\n AffirmDiscount,\n AffirmFailResponse,\n AffirmItem,\n AffirmRequestData,\n AffirmSuccessResponse,\n} from './affirm';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nexport default class AffirmPaymentStrategy implements PaymentStrategy {\n private affirm?: Affirm;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private affirmScriptLoader: AffirmScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const {\n clientToken,\n config: { testMode },\n } = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.affirm = await this.affirmScriptLoader.load(clientToken, testMode);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const methodId = payload.payment?.methodId;\n const { useStoreCredit } = payload;\n\n if (!this.affirm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this.paymentIntegrationService.submitOrder({ useStoreCredit }, options);\n\n const affirmCheckout = await this.initializeAffirmCheckout();\n\n const paymentPayload = {\n methodId,\n paymentData: { nonce: affirmCheckout.checkout_token },\n };\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n deinitialize(): Promise {\n if (this.affirm) {\n this.affirm = undefined;\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private initializeAffirmCheckout(): Promise {\n this.affirm?.checkout(this.getCheckoutInformation());\n\n return new Promise((resolve, reject) => {\n this.affirm?.checkout.open({\n onFail: (failObject: AffirmFailResponse) => {\n if (failObject.reason === 'canceled') {\n reject(new PaymentMethodCancelledError());\n } else {\n reject(new PaymentMethodInvalidError());\n }\n },\n onSuccess: (successObject) => {\n resolve(successObject);\n },\n });\n this.affirm?.ui.error.on('close', () => {\n reject(new PaymentMethodCancelledError());\n });\n });\n }\n\n private getCheckoutInformation(): AffirmRequestData {\n const state = this.paymentIntegrationService.getState();\n const config = state.getStoreConfig();\n const consignments = state.getConsignments();\n const order = state.getOrder();\n const cart = state.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!order) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const amountTransformer = new AmountTransformer(order.currency.decimalPlaces);\n const billingAddress = this.getBillingAddress();\n\n const retrievedShippingAddress = this.getShippingAddress();\n const shippingAddress =\n itemsRequireShipping(cart, config) && retrievedShippingAddress\n ? retrievedShippingAddress\n : billingAddress;\n\n return {\n merchant: {\n user_confirmation_url: config.links.checkoutLink,\n user_cancel_url: config.links.checkoutLink,\n user_confirmation_url_action: 'POST',\n },\n shipping: shippingAddress,\n billing: billingAddress,\n items: this.getItems(amountTransformer, order),\n metadata: {\n shipping_type: this.getShippingType(consignments),\n mode: 'modal',\n platform_type: 'BigCommerce',\n platform_version: '',\n platform_affirm: '',\n },\n discounts: this.getDiscounts(amountTransformer, order),\n order_id: order.orderId ? order.orderId.toString() : '',\n shipping_amount: amountTransformer.toInteger(order.shippingCostTotal),\n tax_amount: amountTransformer.toInteger(order.taxTotal),\n total: amountTransformer.toInteger(order.orderAmount),\n };\n }\n\n private getShippingType(consignments?: Consignment[]): string {\n if (!consignments) {\n return '';\n }\n\n const consignment = consignments[0];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return consignment?.selectedShippingOption ? consignment.selectedShippingOption.type : '';\n }\n\n private getBillingAddress(): AffirmAddress {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const billingInformation = {\n name: {\n first: billingAddress.firstName,\n last: billingAddress.lastName,\n full: `${billingAddress.firstName} ${billingAddress.lastName}`,\n },\n address: {\n line1: billingAddress.address1,\n line2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.stateOrProvinceCode,\n zipcode: billingAddress.postalCode,\n country: billingAddress.countryCode,\n },\n phone_number: billingAddress.phone,\n email: billingAddress.email,\n };\n\n return billingInformation;\n }\n\n private getShippingAddress(): AffirmAddress | undefined {\n const state = this.paymentIntegrationService.getState();\n const shippingAddress = state.getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n const shippingInformation = {\n name: {\n first: shippingAddress.firstName,\n last: shippingAddress.lastName,\n full: `${shippingAddress.firstName} ${shippingAddress.lastName}`,\n },\n address: {\n line1: shippingAddress.address1,\n line2: shippingAddress.address2,\n city: shippingAddress.city,\n state: shippingAddress.stateOrProvinceCode,\n zipcode: shippingAddress.postalCode,\n country: shippingAddress.countryCode,\n },\n phone_number: shippingAddress.phone,\n };\n\n return shippingInformation;\n }\n\n private getItems(amountTransformer: AmountTransformer, order: Order): AffirmItem[] {\n const items: AffirmItem[] = [];\n\n order.lineItems.physicalItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this.getCategories(item.categories),\n });\n });\n\n order.lineItems.digitalItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this.getCategories(item.categories),\n });\n });\n\n order.lineItems.giftCertificates.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: '',\n unit_price: amountTransformer.toInteger(item.amount),\n qty: 1,\n item_image_url: '',\n item_url: '',\n });\n });\n\n if (order.lineItems.customItems) {\n order.lineItems.customItems.forEach((item) => {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.listPrice),\n qty: item.quantity,\n item_image_url: '',\n item_url: '',\n });\n });\n }\n\n return items;\n }\n\n private getDiscounts(amountTransformer: AmountTransformer, order: Order): AffirmDiscount {\n const discounts: AffirmDiscount = {};\n\n order.coupons.forEach((line) => {\n if (line.discountedAmount > 0) {\n discounts[line.code] = {\n discount_amount: amountTransformer.toInteger(line.discountedAmount),\n discount_display_name: line.displayName,\n };\n }\n });\n\n if (order.discountAmount > 0) {\n discounts.DISCOUNTED_AMOUNT = {\n discount_amount: amountTransformer.toInteger(order.discountAmount),\n discount_display_name: 'discount',\n };\n }\n\n return discounts;\n }\n\n private getCategories(categories?: LineItemCategory[][]): string[][] {\n if (!categories) {\n return [[]];\n }\n\n return categories.map((categoryTree) => categoryTree.map((category) => category.name));\n }\n}\n","export interface Affirm {\n checkout: AffirmCheckout;\n ui: {\n error: {\n on(event: string, callback: () => void): void;\n };\n ready(callback: () => void): void;\n };\n}\n\nexport interface AffirmCheckout {\n (options: AffirmRequestData): void;\n open(modalOptions: AffirmCallback): void;\n init(): void;\n}\n\ninterface AffirmCallback {\n onFail(onFail: AffirmFailResponse): void;\n onSuccess(success: AffirmSuccessResponse): void;\n}\n\nexport interface AffirmHostWindow extends Window {\n affirm?: Affirm;\n}\n\nexport interface AffirmSuccessResponse {\n checkout_token: string;\n created: string;\n}\n\nexport interface AffirmFailResponse {\n reason: string;\n}\n\nexport interface AffirmRequestData {\n merchant: {\n user_confirmation_url: string;\n user_cancel_url: string;\n user_confirmation_url_action?: string;\n name?: string;\n };\n shipping: AffirmAddress;\n billing?: AffirmAddress;\n items: AffirmItem[];\n discounts: AffirmDiscount;\n metadata: {\n shipping_type: string;\n entity_name?: string;\n webhook_session_id?: string;\n mode?: string;\n platform_type: string;\n platform_version: string;\n platform_affirm: string;\n };\n order_id?: string;\n shipping_amount: number;\n tax_amount: number;\n total: number;\n}\n\nexport interface AffirmItem {\n display_name: string;\n sku: string;\n unit_price: number;\n qty: number;\n item_image_url: string;\n item_url: string;\n categories?: string[][];\n}\n\nexport interface AffirmDiscount {\n [key: string]: {\n discount_amount: number;\n discount_display_name: string;\n };\n}\n\nexport interface AffirmAddress {\n name: {\n first: string;\n last: string;\n full?: string;\n };\n address: {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n zipcode: string;\n country?: string;\n };\n phone_number?: string;\n email?: string;\n}\n\nexport enum AFFIRM_SCRIPTS {\n PROD = '//cdn1.affirm.com/js/v2/affirm.js',\n SANDBOX = '//cdn1-sandbox.affirm.com/js/v2/affirm.js',\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Affirm, AFFIRM_SCRIPTS, AffirmHostWindow } from './affirm';\nimport loadAffirmJS from './affirmJs';\n\nexport default class AffirmScriptLoader {\n constructor(public affirmWindow: AffirmHostWindow = window) {}\n\n load(apikey = '', testMode?: boolean): Promise {\n const scriptURI = testMode ? AFFIRM_SCRIPTS.SANDBOX : AFFIRM_SCRIPTS.PROD;\n\n loadAffirmJS(apikey, scriptURI);\n\n if (!this.affirmWindow.affirm) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(this.affirmWindow.affirm);\n }\n}\n","/* istanbul ignore file */\n\n/* eslint-disable prefer-rest-params */\n/* eslint-disable @typescript-eslint/no-empty-function */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable no-plusplus */\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-shadow */\n/* eslint-disable no-underscore-dangle */\n/**\n * Used this approach as Affirm uses snipped for initializing. Please refer to Affirm documentation in: https://docs.affirm.com/Integrate_Affirm/Direct_API#1._Add_Affirm.js\n */\nimport { Affirm, AffirmHostWindow } from './affirm';\n\ninterface AffirmConfig {\n public_api_key: string;\n script: string;\n}\n\nexport default function loadAffirmJS(apiKey: string, scriptURL: string) {\n const _AFFIRM_CONFIG: AffirmConfig = {\n public_api_key: apiKey,\n script: scriptURL,\n };\n\n (function foo(\n m: AffirmHostWindow | any,\n g: AffirmConfig,\n n: 'affirm',\n d: 'checkout',\n a: 'ui',\n e: 'script',\n h: 'ready',\n c: 'jsReady',\n ) {\n const b = m[n] || {};\n const k = document.createElement(e);\n const p = document.getElementsByTagName(e)[0];\n const l = function bar(a: Affirm | any, b: keyof Affirm, c: string) {\n return function baz() {\n a[b]._.push([c, arguments]);\n };\n };\n\n b[d] = l(b, d, 'set');\n\n const f = b[d];\n\n b[a] = {};\n b[a]._ = [];\n f._ = [];\n b._ = [];\n b[a][h] = l(b, a, h);\n\n b[c] = function qux() {\n b._.push([h, arguments]);\n };\n\n let a1 = 0;\n\n for (\n const c1 = 'set add save post open empty reset on off trigger ready setProduct'.split(\n ' ',\n );\n a1 < c1.length;\n a1++\n ) {\n f[c1[a1]] = l(b, d, c1[a1]);\n }\n\n let a2 = 0;\n\n for (const c2 = ['get', 'token', 'url', 'items']; a2 < c2.length; a2++) {\n f[c2[a2]] = function foobar() {};\n }\n\n k.async = !0;\n k.src = g[e];\n\n if (p.parentNode) {\n p.parentNode.insertBefore(k, p);\n }\n\n delete (g as Partial)[e];\n f(g);\n m[n] = b;\n })(window, _AFFIRM_CONFIG, 'affirm', 'checkout', 'ui', 'script', 'ready', 'jsReady');\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AffirmPaymentStrategy from './affirm-payment-strategy';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nconst createAffirmPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AffirmPaymentStrategy(paymentIntegrationService, new AffirmScriptLoader());\n};\n\nexport default toResolvableModule(createAffirmPaymentStrategy, [{ id: 'affirm' }]);\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the order finalization request\n * was not completed successfully.\n */\nexport default class OrderFinalizationNotCompletedError extends StandardError {\n constructor(message?: string) {\n super(message || 'The current order could not be finalized successfully');\n\n this.name = 'OrderFinalizationNotCompletedError';\n this.type = 'order_finalization_not_completed';\n }\n}\n","import {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotCompletedError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpayScriptLoader from './afterpay-script-loader';\nimport AfterpaySdk from './afterpay-sdk';\n\nexport default class AfterpayPaymentStrategy implements PaymentStrategy {\n private _afterpaySdk?: AfterpaySdk;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _afterpayScriptLoader: AfterpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethod(options.methodId, options.gatewayId);\n const currencyCode = state.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(paymentMethod, countryCode);\n }\n\n deinitialize(): Promise {\n if (this._afterpaySdk) {\n this._afterpaySdk = undefined;\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { useStoreCredit } = payload;\n\n if (useStoreCredit !== undefined) {\n await this._paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this._loadPaymentMethod(gatewayId, methodId, options);\n\n const state = this._paymentIntegrationService.getState();\n\n await this._paymentIntegrationService.validateCheckout(state.getCheckout(), options);\n\n const currencyCode = state.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n this._redirectToAfterpay(countryCode, state.getPaymentMethod(methodId, gatewayId));\n\n // Afterpay will handle the rest of the flow so return a promise that doesn't really resolve\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Promise(() => {});\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n const config = state.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config?.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._paymentIntegrationService.submitOrder({}, options);\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._paymentIntegrationService.forgetCheckout(payment.providerId);\n await this._paymentIntegrationService.loadPaymentMethods();\n\n if (isRequestError(error)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-member-access\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n }\n\n private _redirectToAfterpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._afterpaySdk || !paymentMethod?.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._afterpaySdk.initialize({ countryCode });\n this._afterpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _mapCurrencyToISO2(currencyCode: string): string {\n const countryByCurrency: { [key: string]: string } = {\n AUD: 'AU',\n NZD: 'NZ',\n CAD: 'CA',\n USD: 'US',\n };\n\n return countryByCurrency[currencyCode] || 'AU';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n });\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Afterpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpaySdk from './afterpay-sdk';\nimport isAfterpayWindow from './is-afterpay-window';\n\nenum SCRIPTS_DEFAULT {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal-sandbox.afterpay.com/afterpay-async.js',\n}\n\nenum SCRIPTS_US {\n PROD = '//portal.afterpay.com/afterpay-async.js',\n SANDBOX = '//portal.sandbox.afterpay.com/afterpay-async.js',\n}\n\n/** Class responsible for loading the Afterpay SDK */\nexport default class AfterpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n /**\n * Loads the appropriate Afterpay SDK depending on the payment method data.\n *\n * @param {PaymentMethod} method the payment method data\n */\n async load(method: PaymentMethod, countryCode: string): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode);\n\n return this._scriptLoader.loadScript(scriptURI).then(() => {\n if (!isAfterpayWindow(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return window.AfterPay;\n });\n }\n\n private _getScriptURI(countryCode: string, testMode: boolean): string {\n if (countryCode === 'US') {\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import AfterpayWindow from './afterpay-window';\n\nexport default function isAfterpayWindow(window: Window): window is AfterpayWindow {\n return 'AfterPay' in window;\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AfterpayPaymentStrategy from './afterpay-payment-strategy';\nimport AfterpayScriptLoader from './afterpay-script-loader';\n\nconst createAfterpayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AfterpayPaymentStrategy(\n paymentIntegrationService,\n new AfterpayScriptLoader(createScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createAfterpayPaymentStrategy, [\n { gateway: 'afterpay' },\n { id: 'afterpay' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n isAmazonPayAdditionalActionErrorBody,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CheckoutSettings,\n guard,\n InvalidArgumentError,\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StoreProfile,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithAmazonPayV2PaymentInitializeOptions } from './amazon-pay-v2-payment-initialize-options';\n\nexport default class AmazonPayV2PaymentStrategy implements PaymentStrategy {\n private _amazonPayButton?: HTMLDivElement;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAmazonPayV2PaymentInitializeOptions,\n ): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const initializationData = paymentMethod.initializationData || {};\n const { paymentToken = '', region = '', isButtonMicroTextDisabled } = initializationData;\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (this._isReadyToPay(paymentToken)) {\n if (amazonpay?.editButtonId) {\n this._bindEditButton(\n amazonpay.editButtonId,\n paymentToken,\n 'changePayment',\n this._isModalFlow(region),\n );\n }\n } else {\n const { id: containerId } = this._createContainer();\n\n this._amazonPayButton = this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: state,\n containerId,\n decoupleCheckoutInitiation: this._isOneTimeTransaction(\n features,\n region.toUpperCase(),\n ),\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n isButtonMicroTextDisabled,\n });\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const state = this.paymentIntegrationService.getState();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const initializationData = paymentMethod.initializationData || {};\n const { paymentToken = '', region = '' } = initializationData;\n\n if (\n this._isReadyToPay(paymentToken) ||\n this._isOneTimeTransaction(features, region.toUpperCase())\n ) {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: paymentToken || 'apb' },\n };\n\n await this.paymentIntegrationService.submitOrder(payload, options);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n return;\n } catch (error) {\n if (!isRequestError(error) || !isAmazonPayAdditionalActionErrorBody(error.body)) {\n throw error;\n }\n\n const { additional_action_required: additionalAction } = error.body;\n const { redirect_url } = additionalAction.data;\n\n if (paymentToken) {\n return new Promise(() => window.location.assign(redirect_url));\n }\n\n this.amazonPayV2PaymentProcessor.prepareCheckout(\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n JSON.parse(redirect_url) as Required,\n );\n }\n }\n\n this._getAmazonPayButton().click();\n\n // Focus of parent window used to try and detect the user cancelling the Amazon log in modal\n // Should be refactored if/when Amazon add a modal close hook to their SDK\n if (this._isModalFlow(region)) {\n return new Promise((_, reject) => {\n const onFocus = () => {\n window.removeEventListener('focus', onFocus);\n reject(\n new PaymentMethodCancelledError(\n 'Shopper needs to login to Amazonpay to continue',\n ),\n );\n };\n\n window.addEventListener('focus', onFocus);\n });\n }\n\n return new Promise(noop);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.amazonPayV2PaymentProcessor.deinitialize();\n\n this._amazonPayButton = undefined;\n }\n\n private _bindEditButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n isModalFlow: boolean,\n ): void {\n const button = document.getElementById(buttonId);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (!isModalFlow) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => {\n void this._showLoadingSpinner();\n });\n }\n\n this.amazonPayV2PaymentProcessor.bindButton(buttonId, sessionId, changeAction);\n }\n\n private _isModalFlow(region: string) {\n return region === 'us';\n }\n\n private async _showLoadingSpinner(): Promise {\n await this.paymentIntegrationService.widgetInteraction(() => new Promise(noop));\n }\n\n private _createContainer(): HTMLElement {\n let container = document.getElementById('AmazonPayButton');\n\n if (container) {\n return container;\n }\n\n container = document.createElement('div');\n container.id = 'AmazonPayButton';\n container.style.display = 'none';\n\n return document.body.appendChild(container);\n }\n\n private _getAmazonPayButton() {\n return guard(\n this._amazonPayButton,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _isOneTimeTransaction(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n return (\n this.amazonPayV2PaymentProcessor.isPh4Enabled(features, storeCountryCode) &&\n features['INT-6399.amazon_pay_apb']\n );\n }\n\n private _isReadyToPay(paymentToken?: string): boolean {\n return !!paymentToken;\n }\n}\n","import { AmazonPayAdditionalActionErrorBody } from './amazon-pay-v2';\n\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nexport function isAmazonPayAdditionalActionErrorBody(\n errorBody: unknown,\n): errorBody is AmazonPayAdditionalActionErrorBody {\n return (\n typeof errorBody === 'object' &&\n errorBody !== null &&\n 'status' in errorBody &&\n 'additional_action_required' in errorBody &&\n (errorBody as AmazonPayAdditionalActionErrorBody).status === 'additional_action_required' &&\n 'data' in (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required &&\n 'redirect_url' in\n (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required.data &&\n typeof (errorBody as AmazonPayAdditionalActionErrorBody).additional_action_required.data\n .redirect_url === 'string'\n );\n}\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n","import { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2PaymentStrategy from './amazon-pay-v2-payment-strategy';\n\nconst createAmazonPayV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AmazonPayV2PaymentStrategy(\n paymentIntegrationService,\n createAmazonPayV2PaymentProcessor(),\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2PaymentStrategy, [{ id: 'amazonpay' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport { WithApplePayPaymentInitializeOptions } from './apple-pay-payment-initialize-options';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\ninterface ApplePayPromise {\n resolve(): void;\n reject(reason?: Error): void;\n}\n\nenum DefaultLabels {\n Shipping = 'Shipping',\n Subtotal = 'Subtotal',\n StoreCredit = 'Store Credit',\n}\n\nexport default class ApplePayPaymentStrategy implements PaymentStrategy {\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _storeCreditLabel: string = DefaultLabels.StoreCredit;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithApplePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n\n this._shippingLabel = options.applepay?.shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = options.applepay?.subtotalLabel || DefaultLabels.Subtotal;\n this._storeCreditLabel = options.applepay?.storeCreditLabel || DefaultLabels.StoreCredit;\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n const state = this._paymentIntegrationService.getState();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const request = this._getBaseRequest(state, paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n await this._paymentIntegrationService.submitOrder(\n {\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n\n applePaySession.begin();\n\n return new Promise((resolve, reject) => {\n this._handleApplePayEvents(applePaySession, paymentMethod, {\n resolve,\n reject,\n });\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _getBaseRequest(\n state: PaymentIntegrationSelectors,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const checkout = state.getCheckoutOrThrow();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const { grandTotal, isStoreCreditApplied, outstandingBalance } = checkout;\n\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n if (isStoreCreditApplied) {\n const { storeCredit } = state.getCustomerOrThrow();\n\n lineItems.push({\n label: this._storeCreditLabel,\n amount: `-${Math.min(grandTotal, storeCredit).toFixed(decimalPlaces)}`,\n });\n }\n\n return {\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems,\n total: {\n label: storeName,\n amount: `${outstandingBalance.toFixed(decimalPlaces)}`,\n type: 'final',\n },\n };\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n throw new Error('Merchant validation failed');\n }\n };\n\n applePaySession.oncancel = async () =>\n promise.reject(new PaymentMethodCancelledError('Continue with applepay'));\n\n applePaySession.onpaymentauthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod, promise);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n const { token } = event.payment;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n try {\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return promise.resolve();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return promise.reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n const state = this._paymentIntegrationService.getState();\n let braintreePaymentMethod =\n state.getPaymentMethod(ApplePayGatewayType.BRAINTREE_FASTLANE) ||\n state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (!braintreePaymentMethod) {\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n }\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayPaymentStrategy from './apple-pay-payment-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectPreviouslyUsedCard, BlueSnapDirectSdk } from '../types';\n\nexport default class BlueSnapDirect3ds {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n\n initialize(blueSnapSdk: BlueSnapDirectSdk) {\n this._blueSnapSdk = blueSnapSdk;\n }\n\n async initialize3ds(\n token: string,\n cardData: BlueSnapDirectPreviouslyUsedCard,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n return new Promise((resolve, reject) => {\n blueSnapSdk.threeDsPaymentsSetup(token, (sdkResponse) => {\n const code = sdkResponse.code;\n\n if (code === '1') {\n return resolve(sdkResponse.threeDSecure.threeDSecureReferenceId);\n }\n\n return reject(new PaymentMethodFailedError());\n });\n\n blueSnapSdk.threeDsPaymentsSubmitData(cardData);\n });\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","// copied from packages/core/src/hosted-form/hosted-field-type.ts\n\nenum HostedFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n CardExpiryVerification = 'cardExpiryVerification',\n}\n\nexport default HostedFieldType;\n","import {\n HostedCardFieldOptionsMap,\n HostedFieldOptionsMap,\n HostedFieldType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return HostedFieldType.CardNumber in fields;\n}\n","import {\n HostedFieldOptionsMap,\n HostedFieldType,\n HostedStoredCardFieldOptionsMap,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedStoredCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardCodeVerification in fields ||\n HostedFieldType.CardNumberVerification in fields\n );\n}\n","import { WithCreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectSdk, BlueSnapDirectThreeDSecureData } from '../types';\nimport isHostedCardFieldOptionsMap from '../utils/is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from '../utils/is-hosted-stored-card-field-options-map';\n\nimport BlueSnapDirect3ds from './bluesnap-direct-3ds';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nexport default class BlueSnapDirectCreditCardPaymentStrategy implements PaymentStrategy {\n private _paymentFieldsToken?: string;\n private _shouldUseHostedFields?: boolean;\n private _blueSnapSdk?: BlueSnapDirectSdk;\n\n constructor(\n private _scriptLoader: BlueSnapDirectScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _blueSnapDirectHostedForm: BlueSnapDirectHostedForm,\n private _blueSnapDirect3ds: BlueSnapDirect3ds,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, creditCard } = options;\n\n if (!gatewayId || !creditCard) {\n throw new InvalidArgumentError();\n }\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId, bigpayToken: creditCard.bigpayToken },\n });\n\n const {\n config: { testMode, is3dsEnabled },\n clientToken,\n } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n this._blueSnapSdk = await this._scriptLoader.load(testMode);\n\n this._paymentFieldsToken = clientToken;\n this._shouldUseHostedFields =\n isHostedCardFieldOptionsMap(creditCard.form.fields) ||\n (isHostedStoredCardFieldOptionsMap(creditCard.form.fields) &&\n !!creditCard.form.fields.cardNumberVerification);\n\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.initialize(this._blueSnapSdk, creditCard.form.fields);\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n }\n }\n\n async execute(payload: OrderRequestBody): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._blueSnapSdk) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData } = payload.payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const pfToken = this._getPaymentFieldsToken();\n let threeDSecureReferenceId;\n\n const { is3dsEnabled } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payload.payment.methodId, payload.payment.gatewayId).config;\n\n const bluesnapSubmitedForm = this._shouldUseHostedFields\n ? await this._blueSnapDirectHostedForm\n .validate()\n .submit(\n is3dsEnabled ? this._getBlueSnapDirectThreeDSecureData() : undefined,\n !(isHostedInstrumentLike(paymentData) && isVaultedInstrument(paymentData)),\n )\n : undefined;\n\n await this._paymentIntegrationService.submitOrder();\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n this._paymentFieldsToken &&\n paymentData.instrumentId\n ) {\n if (is3dsEnabled) {\n this._blueSnapDirect3ds.initialize(this._blueSnapSdk);\n\n const { last4, brand } = this._paymentIntegrationService\n .getState()\n .getCardInstrumentOrThrow(paymentData.instrumentId);\n\n const previouslyUsedCard = {\n last4Digits: last4,\n ccType: brand.toUpperCase(),\n ...this._getBlueSnapDirectThreeDSecureData(),\n };\n\n threeDSecureReferenceId = await this._blueSnapDirect3ds.initialize3ds(\n this._paymentFieldsToken,\n previouslyUsedCard,\n );\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n instrumentId: paymentData.instrumentId,\n ...(this._shouldUseHostedFields ? { nonce: pfToken } : {}),\n ...(threeDSecureReferenceId\n ? { deviceSessionId: threeDSecureReferenceId }\n : {}),\n shouldSetAsDefaultInstrument: !!shouldSetAsDefaultInstrument,\n },\n });\n\n return;\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n pfToken,\n cardHolderName:\n bluesnapSubmitedForm && bluesnapSubmitedForm.cardHolderName,\n }),\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n private _getBlueSnapDirectThreeDSecureData(): BlueSnapDirectThreeDSecureData {\n const {\n getBillingAddress,\n getShippingAddress,\n getCustomer,\n getCheckoutOrThrow,\n getCartOrThrow,\n } = this._paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const shippingAddress = getShippingAddress();\n const email = getCustomer()?.email || billingAddress?.email;\n const phone = billingAddress?.phone || shippingAddress?.phone;\n\n return {\n amount: getCheckoutOrThrow().outstandingBalance,\n currency: getCartOrThrow().currency.code,\n ...(email && { email }),\n ...(phone && { phone }),\n ...(billingAddress && {\n billingFirstName: billingAddress.firstName,\n billingLastName: billingAddress.lastName,\n billingCountry: billingAddress.countryCode,\n billingCity: billingAddress.city,\n billingAddress: `${billingAddress.address1} ${billingAddress.address2}`.trim(),\n billingZip: billingAddress.postalCode,\n }),\n ...(shippingAddress && {\n shippingFirstName: shippingAddress.firstName,\n shippingLastName: shippingAddress.lastName,\n shippingCountry: shippingAddress.countryCode,\n shippingCity: shippingAddress.city,\n shippingAddress: `${shippingAddress.address1} ${shippingAddress.address2}`.trim(),\n shippingZip: shippingAddress.postalCode,\n }),\n };\n }\n\n private _getPaymentFieldsToken(): string {\n return guard(\n this._paymentFieldsToken,\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n }\n}\n","export type BluesnapDirectNocInputAllowedStyle = Pick<\n CSSStyleDeclaration,\n 'color' | 'fontFamily' | 'fontSize' | 'fontWeight'\n>;\n\nexport interface BlueSnapDirectStyleDeclaration {\n [k: string]: string;\n}\n\nexport interface BlueSnapDirectStyle {\n '.invalid'?: BlueSnapDirectStyleDeclaration;\n ':focus'?: BlueSnapDirectStyleDeclaration;\n input?: BlueSnapDirectStyleDeclaration;\n}\n\nexport enum BlueSnapDirectCardType {\n AMEX = 'american-express',\n CHINA_UNION_PAY = 'unionpay',\n DINERS = 'diners-club',\n DISCOVER = 'discover',\n JCB = 'jcb',\n MASTERCARD = 'mastercard',\n UNKNOWN = 'unknown',\n VISA = 'visa',\n}\n\nexport type BlueSnapDirectCardTypeValues = keyof typeof BlueSnapDirectCardType;\n\nexport enum BlueSnapDirectEventOrigin {\n ON_BLUR = 'onBlur',\n ON_SUBMIT = 'onSubmit',\n}\n\nexport enum BlueSnapDirectErrorDescription {\n EMPTY = 'empty',\n INVALID = 'invalid',\n THREE_DS_NOT_ENABLED = '3D Secure is not enabled',\n}\n\nexport type BlueSnapDirectInputValidationErrorDescription = Extract<\n BlueSnapDirectErrorDescription,\n BlueSnapDirectErrorDescription.EMPTY | BlueSnapDirectErrorDescription.INVALID\n>;\n\nexport enum BlueSnapDirectErrorCode {\n CC_NOT_SUPORTED = '22013',\n ERROR_403 = '403',\n ERROR_404 = '404',\n ERROR_500 = '500',\n INVALID_OR_EMPTY = '10',\n SESSION_EXPIRED = '400',\n THREE_DS_AUTH_FAILED = '14101',\n THREE_DS_CLIENT_ERROR = '14103',\n THREE_DS_MISSING_FIELDS = '14102',\n THREE_DS_NOT_ENABLED = '14100',\n TOKEN_EXPIRED = '14040',\n TOKEN_NOT_ASSOCIATED = '14042',\n TOKEN_NOT_FOUND = '14041',\n}\n\nexport enum BlueSnapDirectHostedFieldTagId {\n CardCode = 'cvv',\n CardExpiry = 'exp',\n CardName = 'noc',\n CardNumber = 'ccn',\n}\n\nexport interface BlueSnapDirectHostedPaymentFieldsOptions {\n token: string;\n onFieldEventHandler?: {\n setupComplete?: () => void;\n threeDsChallengeExecuted?: () => void;\n onFocus?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onBlur?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onError?: (\n tagId: BlueSnapDirectHostedFieldTagId | undefined,\n errorCode: BlueSnapDirectErrorCode,\n errorDescription: BlueSnapDirectErrorDescription | undefined,\n eventOrigin: BlueSnapDirectEventOrigin | undefined,\n ) => void;\n onType?: (\n tagId: BlueSnapDirectHostedFieldTagId,\n cardType: BlueSnapDirectCardTypeValues,\n cardData: BlueSnapDirectCardData | undefined,\n ) => void;\n onEnter?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onValid?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n };\n ccnPlaceHolder?: string;\n cvvPlaceHolder?: string;\n expPlaceHolder?: string;\n style?: BlueSnapDirectStyle;\n '3DS'?: boolean;\n}\n\ninterface BlueSnapDirectCallback {\n statusCode: string;\n transactionFraudInfo: {\n fraudSessionId: string;\n };\n}\n\ninterface BlueSnapDirectCardData {\n binCategory: string;\n cardSubType: string;\n ccBin: string;\n ccType: string;\n isRegulatedCard: string;\n issuingCountry: string;\n last4Digits: string;\n}\n\nexport interface BlueSnapDirectCallbackCardData extends BlueSnapDirectCardData {\n cardCategory: string;\n exp: string;\n}\n\ninterface BlueSnapDirectCallbackData extends BlueSnapDirectCallback {\n cardData: BlueSnapDirectCallbackCardData;\n}\n\nexport interface WithBlueSnapDirectCardHolderName {\n cardHolderName?: string;\n}\n\ninterface BlueSnapDirectSubmitError {\n errorCode: string;\n errorDescription: string;\n eventType: string;\n tagId: string;\n}\n\nexport interface BlueSnapDirectCallbackError extends BlueSnapDirectCallback {\n error: BlueSnapDirectSubmitError[];\n}\n\nexport type BlueSnapDirectCallbackResults =\n | BlueSnapDirectCallbackData\n | BlueSnapDirectCallbackError;\n\nexport interface BlueSnapDirectThreeDSecureData {\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirectSdk {\n hostedPaymentFieldsCreate(options: BlueSnapDirectHostedPaymentFieldsOptions): void;\n hostedPaymentFieldsSubmitData(\n callback: (results: BlueSnapDirectCallbackResults) => void,\n threeDSecureData?: BlueSnapDirectThreeDSecureData,\n ): void;\n threeDsPaymentsSetup(\n token: string,\n callback: (reponse: BlueSnapDirect3dsCallbackResponse) => void,\n ): void;\n threeDsPaymentsSubmitData(cardData: BlueSnapDirectPreviouslyUsedCard): void;\n}\n\nexport interface BlueSnapDirectPreviouslyUsedCard {\n last4Digits?: string;\n ccType?: string;\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirect3dsCallbackResponse {\n code: string;\n cardData: BlueSnapDirectCallbackCardData;\n threeDSecure: {\n authResult: string;\n threeDSecureReferenceId: string;\n };\n}\n\nexport interface BlueSnapDirectHostWindow extends Window {\n bluesnap?: BlueSnapDirectSdk;\n}\n\nexport interface BlueSnapDirectStyleProps {\n border?: string;\n height?: string;\n width?: string;\n}\n\nexport interface BlueSnapDirectRedirectResponseProviderData {\n [key: string]: string;\n merchantid: string;\n}\n\nexport interface BlueSnapDirectRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data?: string;\n };\n}\n\n/**\n * A set of options that are required to initialize the BlueSnap V2 payment\n * method.\n *\n * The payment step is done through a web page via an iframe provided by the\n * strategy.\n *\n * ```html\n * \n *
\n *\n * \n * \n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'bluesnapDirect',\n * bluesnapDirect: {\n * onLoad: (iframe) => {\n * document.getElementById('container')\n * .appendChild(iframe);\n *\n * document.getElementById('cancel-button')\n * .addEventListener('click', () => {\n * document.getElementById('container').innerHTML = '';\n * });\n * },\n * },\n * });\n * ```\n */\nexport interface BlueSnapDirectAPMInitializeOptions {\n /**\n * A set of CSS properties to apply to the iframe.\n */\n style?: BlueSnapDirectStyleProps;\n\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param iframe - The iframe element containing the payment web page\n * provided by the strategy.\n * @param cancel - A function, when called, will cancel the payment\n * process and remove the iframe.\n */\n onLoad(iframe: HTMLIFrameElement, cancel: () => void): void;\n}\n\nexport interface WithBlueSnapDirectAPMPaymentInitializeOptions {\n /**\n * The options that are required to initialize the Apple Pay payment\n * method. They can be omitted unless you need to support Apple Pay.\n */\n bluesnapdirect?: BlueSnapDirectAPMInitializeOptions;\n}\n","import { HostedFieldType } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostedFieldTagId as HostedFieldTagId } from './types';\n\nexport const BlueSnapHostedFieldType: {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber;\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry;\n [HostedFieldTagId.CardName]: HostedFieldType.CardName;\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode;\n} = {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber,\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry,\n [HostedFieldTagId.CardName]: HostedFieldType.CardName,\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode,\n};\n\nexport const CREDIT_CARD_ERRORS = {\n empty: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date is required',\n type: 'required',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n invalid: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date must be a valid future date in MM / YY format',\n type: 'invalid_card_expiry',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n};\n","import { kebabCase } from 'lodash';\n\nimport { CreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldOptionsMap,\n HostedFieldStylesMap,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType } from '../bluesnap-direct-constants';\nimport {\n BlueSnapDirectSdk,\n BlueSnapDirectStyle,\n BlueSnapDirectCallbackCardData as CallbackCardData,\n BlueSnapDirectCallbackError as CallbackError,\n BlueSnapDirectCallbackResults as CallbackResults,\n WithBlueSnapDirectCardHolderName as CardHolderName,\n BlueSnapDirectCardType as CardType,\n BlueSnapDirectCardTypeValues as CardTypeValues,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectThreeDSecureData as ThreeDSecureData,\n} from '../types';\nimport isValidationErrorDescription from '../utils/is-bluesnap-direct-input-validation-error-description';\nimport isHostedCardFieldOptionsMap from '../utils/is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from '../utils/is-hosted-stored-card-field-options-map';\n\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\n\nexport default class BlueSnapDirectHostedForm {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n private _onValidate: HostedFormOptions['onValidate'];\n\n constructor(\n private _nameOnCardInput: BluesnapDirectNameOnCardInput,\n private _hostedInputValidator: BlueSnapHostedInputValidator,\n ) {}\n\n initialize(blueSnapSdk: BlueSnapDirectSdk, fields?: HostedFieldOptionsMap) {\n this._blueSnapSdk = blueSnapSdk;\n\n if (!fields) {\n return;\n }\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._hostedInputValidator.initialize();\n\n return;\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields) && !!fields.cardNumberVerification) {\n this._hostedInputValidator.initializeValidationFields();\n }\n }\n\n async attach(\n paymentFieldsToken: string,\n { form: { fields, ...callbacksAndStyles } }: CreditCardPaymentInitializeOptions,\n enable3DS = false,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n if (!isHostedCardFieldOptionsMap(fields) && !isHostedStoredCardFieldOptionsMap(fields)) {\n throw new InvalidArgumentError(\n 'Field options must be of type HostedCardFieldOptionsMap',\n );\n }\n\n this._onValidate = callbacksAndStyles.onValidate;\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._setCustomBlueSnapAttributes(fields);\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields)) {\n this._setCustomStoredCardsBlueSnapAttributes(fields);\n }\n\n return new Promise((resolve) => {\n const options = this._getHostedPaymentFieldsOptions(\n paymentFieldsToken,\n fields,\n callbacksAndStyles,\n resolve,\n enable3DS,\n );\n\n blueSnapSdk.hostedPaymentFieldsCreate(options);\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._nameOnCardInput.attach(\n options,\n fields.cardName.accessibilityLabel,\n fields.cardName.placeholder,\n );\n }\n });\n }\n\n validate(): this {\n const results = this._hostedInputValidator.validate();\n\n this._onValidate?.(results);\n\n if (!results.isValid) {\n const details = Object.entries(results.errors).reduce(\n (result, [key, value]: [string, HostedInputValidateErrorData[]]) => ({\n ...result,\n [key]: value.map(({ message, type }) => ({ message, type })),\n }),\n {},\n );\n\n throw new PaymentInvalidFormError(details);\n }\n\n return this;\n }\n\n submit(\n threeDSecureData?: ThreeDSecureData,\n shouldSendName = false,\n ): Promise {\n return new Promise((resolve, reject) =>\n this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(\n (data: CallbackResults) =>\n this._isBlueSnapDirectCallbackError(data)\n ? reject(\n new PaymentMethodFailedError(\n data.statusCode === ErrorCode.THREE_DS_AUTH_FAILED\n ? data.error[0].errorDescription\n : `Submission failed with status: ${\n data.statusCode\n } and errors: ${JSON.stringify(data.error)}`,\n ),\n )\n : resolve({\n ...data.cardData,\n ...(shouldSendName\n ? { cardHolderName: this._nameOnCardInput.getValue() }\n : {}),\n }),\n threeDSecureData,\n ),\n );\n }\n\n detach(): void {\n this._nameOnCardInput.detach();\n }\n\n private _isBlueSnapDirectCallbackError(data: CallbackResults): data is CallbackError {\n return 'error' in data;\n }\n\n private _getHostedPaymentFieldsOptions(\n token: string,\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n {\n onFocus,\n onBlur,\n onValidate,\n onCardTypeChange,\n onEnter,\n styles,\n }: Omit,\n resolve: () => void,\n enable3DS: boolean,\n ): HostedPaymentFieldsOptions {\n return {\n token,\n onFieldEventHandler: {\n setupComplete: () => resolve(),\n onFocus: this._usetUiEventCallback(onFocus),\n onBlur: this._usetUiEventCallback(onBlur),\n onError: this._handleError(onValidate),\n onType: (_tagId: HostedFieldTagId, cardType: CardTypeValues) =>\n onCardTypeChange?.({ cardType: CardType[cardType] }),\n onEnter: this._usetUiEventCallback(onEnter),\n onValid: (tagId: HostedFieldTagId) =>\n onValidate?.(this._hostedInputValidator.validate({ tagId })),\n },\n ...(isHostedCardFieldOptionsMap(fields) && {\n ccnPlaceHolder: fields.cardNumber.placeholder || '',\n cvvPlaceHolder: fields.cardCode?.placeholder || '',\n expPlaceHolder: fields.cardExpiry.placeholder || 'MM / YY',\n }),\n ...(styles && { style: this._mapStyles(styles) }),\n '3DS': enable3DS,\n };\n }\n\n private _mapStyles({\n default: input,\n error,\n focus,\n }: HostedFieldStylesMap): BlueSnapDirectStyle {\n return Object.entries({\n ...(input && { input }),\n ...(error && { '.invalid': error }),\n ...(focus && { ':focus': focus }),\n }).reduce((result, [selector, declaration]) => {\n return {\n ...result,\n [selector]: Object.entries(declaration).reduce(\n (declarationBlock, [property, value]) => ({\n ...declarationBlock,\n [kebabCase(property)]: value,\n }),\n {},\n ),\n };\n }, {});\n }\n\n private _handleError(\n onValidate: HostedFormOptions['onValidate'],\n ): (\n tagId: HostedFieldTagId | undefined,\n errorCode: ErrorCode,\n errorDescription: ErrorDescription | undefined,\n eventOrigin: EventOrigin | undefined,\n ) => void {\n return (tagId, errorCode, errorDescription, eventOrigin) => {\n if (errorCode === ErrorCode.INVALID_OR_EMPTY) {\n if (tagId && isValidationErrorDescription(errorDescription)) {\n return onValidate?.(\n this._hostedInputValidator.validate({ tagId, errorDescription }),\n );\n }\n }\n\n throw new PaymentMethodFailedError(\n `An unexpected error has occurred: ${JSON.stringify({\n tagId,\n errorCode,\n errorDescription,\n eventOrigin,\n })}`,\n );\n };\n }\n\n private _usetUiEventCallback(\n callback?: (\n data: HostedFieldBlurEventData | HostedFieldEnterEventData | HostedFieldFocusEventData,\n ) => void,\n ): (tagId: HostedFieldTagId) => void {\n return (tagId) => {\n if (callback) {\n callback({ fieldType: BlueSnapHostedFieldType[tagId] });\n }\n };\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _setCustomBlueSnapAttributes(fields: HostedCardFieldOptionsMap): void {\n const { cardNumber, cardExpiry, cardCode, cardName } = fields;\n\n const cardNumberContainer = document.getElementById(cardNumber.containerId);\n const cardExpiryContainer = document.getElementById(cardExpiry.containerId);\n const cardCodeContainer = cardCode && document.getElementById(cardCode.containerId);\n const cardNameContainer = document.getElementById(cardName.containerId);\n\n if (\n !cardNumberContainer ||\n !cardExpiryContainer ||\n !cardCodeContainer ||\n !cardNameContainer\n ) {\n throw new InvalidArgumentError(\n 'Unable to create hosted payment fields to invalid HTML container elements.',\n );\n }\n\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n cardExpiryContainer.dataset.bluesnap = HostedFieldTagId.CardExpiry;\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n cardNameContainer.dataset.bluesnap = HostedFieldTagId.CardName;\n }\n\n private _setCustomStoredCardsBlueSnapAttributes(fields: HostedStoredCardFieldOptionsMap): void {\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n const cardNumberContainer =\n cardNumberVerification && document.getElementById(cardNumberVerification.containerId);\n const cardCodeContainer =\n cardCodeVerification && document.getElementById(cardCodeVerification.containerId);\n\n if (!cardNumberContainer && !cardCodeContainer) {\n return;\n }\n\n if (cardNumberContainer) {\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n }\n\n if (cardCodeContainer) {\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n }\n }\n}\n","import {\n BlueSnapDirectErrorDescription,\n BlueSnapDirectInputValidationErrorDescription,\n} from '../types';\n\nexport default function isBlueSnapDirectInputValidationErrorDescription(\n errorDescription?: BlueSnapDirectErrorDescription,\n): errorDescription is BlueSnapDirectInputValidationErrorDescription {\n if (errorDescription === undefined) {\n return false;\n }\n\n return [BlueSnapDirectErrorDescription.EMPTY, BlueSnapDirectErrorDescription.INVALID].includes(\n errorDescription,\n );\n}\n","import {\n HostedFieldType,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInputValidateResults,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType, CREDIT_CARD_ERRORS } from '../bluesnap-direct-constants';\nimport {\n BlueSnapDirectInputValidationErrorDescription as ErrorDescription,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n} from '../types';\n\nexport default class BlueSnapHostedInputValidator {\n private _errors: HostedInputValidateErrorDataMap = {};\n\n initialize(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardExpiry: [CREDIT_CARD_ERRORS.empty.cardExpiry],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n cardName: [CREDIT_CARD_ERRORS.empty.cardName],\n };\n }\n\n initializeValidationFields(): void {\n this._errors = {\n cardNumberVerification: [CREDIT_CARD_ERRORS.empty.cardNumber],\n };\n }\n\n validate(error?: {\n tagId: HostedFieldTagId;\n errorDescription?: ErrorDescription;\n }): HostedInputValidateResults {\n if (error) {\n this._updateErrors(error.tagId, error.errorDescription);\n }\n\n return {\n isValid: Object.values(this._errors).every(\n (errorData: HostedInputValidateErrorData[]) => errorData.length === 0,\n ),\n errors: this._errors,\n };\n }\n\n private _updateErrors(tagId: HostedFieldTagId, errorDescription?: ErrorDescription): void {\n const fieldType = this._errors.cardNumberVerification\n ? HostedFieldType.CardNumberVerification\n : BlueSnapHostedFieldType[tagId];\n\n this._errors[fieldType] = errorDescription\n ? [CREDIT_CARD_ERRORS[errorDescription][fieldType]]\n : [];\n }\n}\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BluesnapDirectNocInputAllowedStyle as AllowedStyle,\n BlueSnapDirectStyle,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectStyleDeclaration as StyleDeclaration,\n} from '../types';\nimport isArrayOfAllowedProps from '../utils/is-array-of-allowed-props';\n\nexport default class BluesnapDirectNameOnCardInput {\n private _input?: HTMLInputElement;\n private _style?: BlueSnapDirectStyle;\n\n attach(\n {\n style,\n onFieldEventHandler: { onFocus, onBlur, onValid, onError, onEnter } = {},\n }: HostedPaymentFieldsOptions,\n accessibilityLabel?: string,\n placeholder?: string,\n ): void {\n this._style = style;\n\n this._create();\n\n this._getInput().addEventListener('focus', this._handleFocus(onFocus));\n this._getInput().addEventListener('blur', this._handleBlur(onBlur, onValid, onError));\n this._getInput().addEventListener('enter', this._handleEnter(onEnter));\n\n if (accessibilityLabel) {\n this._getInput().setAttribute('aria-label', accessibilityLabel);\n }\n\n if (placeholder) {\n this._getInput().placeholder = placeholder;\n }\n\n document.querySelector('[data-bluesnap=\"noc\"]')?.appendChild(this._getInput());\n }\n\n getValue(): string {\n return this._getInput().value;\n }\n\n detach(): void {\n if (this._input) {\n this._input.remove();\n this._input = undefined;\n }\n }\n\n private _handleFocus(\n onFocus: Required['onFieldEventHandler']['onFocus'],\n ): (event: Event) => void {\n return () => {\n this._applyStyles(this._style?.[':focus']);\n\n onFocus?.(HostedFieldTagId.CardName);\n };\n }\n\n private _handleBlur(\n onBlur: Required['onFieldEventHandler']['onBlur'],\n onValid: Required['onFieldEventHandler']['onValid'],\n onError: Required['onFieldEventHandler']['onError'],\n ): (event: Event) => void {\n return ({ target }) => {\n onBlur?.(HostedFieldTagId.CardName);\n\n if (target instanceof HTMLInputElement) {\n if (/\\w{1,200}/.test(target.value)) {\n this._applyStyles(this._style?.input);\n\n onValid?.(HostedFieldTagId.CardName);\n } else {\n this._applyStyles(this._style?.['.invalid']);\n\n onError?.(\n HostedFieldTagId.CardName,\n ErrorCode.INVALID_OR_EMPTY,\n ErrorDescription.EMPTY,\n EventOrigin.ON_BLUR,\n );\n }\n }\n };\n }\n\n private _handleEnter(\n onEnter: Required['onFieldEventHandler']['onEnter'],\n ): (event: Event) => void {\n return () => onEnter?.(HostedFieldTagId.CardName);\n }\n\n private _applyStyles(styles: StyleDeclaration = {}): void {\n const allowedStyle: AllowedStyle = {\n color: styles.color,\n fontFamily: styles['font-family'],\n fontSize: styles['font-size'],\n fontWeight: styles['font-weight'],\n };\n const styleKeys = Object.keys(allowedStyle);\n\n if (isArrayOfAllowedProps(styleKeys)) {\n styleKeys.forEach((key) => {\n if (!allowedStyle[key]) {\n return;\n }\n\n this._getInput().style[key] = allowedStyle[key] || '';\n });\n }\n }\n\n private _configureInput(): void {\n this._getInput().autocomplete = 'cc-name';\n this._getInput().id = HostedFieldTagId.CardName;\n this._getInput().inputMode = 'text';\n this._getInput().maxLength = 200;\n this._getInput().style.backgroundColor = 'transparent';\n this._getInput().style.border = '0';\n this._getInput().style.height = '100%';\n this._getInput().style.margin = '0';\n this._getInput().style.outline = 'none';\n this._getInput().style.padding = '0';\n this._getInput().style.width = '100%';\n this._getInput().type = 'text';\n }\n\n private _getInput(): HTMLInputElement {\n return guard(\n this._input,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _create(): void {\n this._input = document.createElement('input');\n this._configureInput();\n this._applyStyles(this._style?.input);\n }\n}\n","import { BluesnapDirectNocInputAllowedStyle } from '../types';\n\nexport default function isArrayOfAllowedProps(\n fields: string[],\n): fields is Array {\n return fields.every((field) =>\n ['color', 'fontFamily', 'fontSize', 'fontWeight'].includes(field),\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostWindow, BlueSnapDirectSdk } from '../types';\n\nexport enum BlueSnapDirectSdkEnv {\n PRODUCTION = 'https://pay.bluesnap.com/web-sdk/5/bluesnap.js',\n SANDBOX = 'https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js',\n}\n\nexport default class BlueSnapDirectScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BlueSnapDirectHostWindow = window,\n ) {}\n\n async load(testMode = false): Promise {\n if (this._window.bluesnap) {\n return this._window.bluesnap;\n }\n\n await this._scriptLoader.loadScript(\n testMode ? BlueSnapDirectSdkEnv.SANDBOX : BlueSnapDirectSdkEnv.PRODUCTION,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this._window.bluesnap) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.bluesnap;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirect3ds from './bluesnap-direct-3ds';\nimport BlueSnapDirectCreditCardPaymentStrategy from './bluesnap-direct-credit-card-payment-strategy';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nconst createBlueSnapDirectCreditCardPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectCreditCardPaymentStrategy\n> = (paymentIntegrationService) =>\n new BlueSnapDirectCreditCardPaymentStrategy(\n new BlueSnapDirectScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n new BlueSnapDirectHostedForm(\n new BluesnapDirectNameOnCardInput(),\n new BlueSnapHostedInputValidator(),\n ),\n new BlueSnapDirect3ds(),\n );\n\nexport default toResolvableModule(createBlueSnapDirectCreditCardPaymentStrategy, [\n { id: 'credit_card', gateway: 'bluesnapdirect' },\n]);\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectRedirectResponse } from '../types';\nimport {\n isEcpInstrument,\n isIdealInstrument,\n isPayByBankInstrument,\n isSepaInstrument,\n} from '../utils/is-bluesnap-direct-instrument';\nimport isBlueSnapDirectRedirectResponseProviderData from '../utils/is-bluesnap-direct-provider-data';\n\nexport default class BlueSnapDirectAPMPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody): Promise {\n const paymentPayload = this._formatePaymentPayload(payload);\n\n await this._paymentIntegrationService.submitOrder();\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n if (this._isBlueSnapDirectRedirectResponse(error)) {\n const providerData: unknown =\n error.body.provider_data && JSON.parse(error.body.provider_data);\n\n let frameUrl = error.body.additional_action_required.data.redirect_url;\n\n if (isBlueSnapDirectRedirectResponseProviderData(providerData)) {\n const providerDataQuery = new URLSearchParams(providerData).toString();\n\n frameUrl = `${frameUrl}&${providerDataQuery}`;\n }\n\n return new Promise(() => window.location.replace(frameUrl));\n }\n\n return Promise.reject(error);\n }\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _formatePaymentPayload({ payment }: OrderRequestBody) {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (\n payment.paymentData &&\n isVaultedInstrument(payment.paymentData) &&\n isHostedInstrumentLike(payment.paymentData)\n ) {\n return {\n ...payment,\n paymentData: {\n instrumentId: payment.paymentData.instrumentId,\n shouldSetAsDefaultInstrument:\n !!payment.paymentData.shouldSetAsDefaultInstrument,\n },\n };\n }\n\n if (isEcpInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n ecp: {\n account_number: payment.paymentData.accountNumber,\n account_type: payment.paymentData.accountType,\n shopper_permission: payment.paymentData.shopperPermission,\n routing_number: payment.paymentData.routingNumber,\n },\n vault_payment_instrument: payment.paymentData.shouldSaveInstrument,\n set_as_default_stored_instrument:\n payment.paymentData.shouldSetAsDefaultInstrument,\n },\n },\n };\n }\n\n if (isSepaInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n sepa_direct_debit: {\n iban: payment.paymentData.iban,\n first_name: payment.paymentData.firstName,\n last_name: payment.paymentData.lastName,\n shopper_permission: payment.paymentData.shopperPermission,\n },\n vault_payment_instrument: payment.paymentData.shouldSaveInstrument,\n set_as_default_stored_instrument:\n payment.paymentData.shouldSetAsDefaultInstrument,\n },\n },\n };\n }\n\n if (isIdealInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n ideal: {\n bic: payment.paymentData.bic,\n },\n },\n },\n };\n }\n\n if (isPayByBankInstrument(payment.paymentData)) {\n return {\n ...payment,\n paymentData: {\n formattedPayload: {\n pay_by_bank: {\n iban: payment.paymentData.iban,\n },\n },\n },\n };\n }\n\n return {\n methodId: payment.methodId,\n };\n }\n\n private _isBlueSnapDirectRedirectResponse(\n response: unknown,\n ): response is BlueSnapDirectRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data.redirect_url\n );\n }\n}\n","import { BlueSnapDirectRedirectResponseProviderData } from '../types';\n\nexport default function isBlueSnapDirectRedirectResponseProviderData(\n value: unknown,\n): value is BlueSnapDirectRedirectResponseProviderData {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const partialValue: Partial = value;\n\n if (!partialValue.merchantid) {\n return false;\n }\n\n return typeof partialValue.merchantid === 'string';\n}\n","import {\n WithEcpInstrument,\n WithIdealInstrument,\n WithPayByBankInstrument,\n WithSepaInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport function isEcpInstrument(data: unknown): data is WithEcpInstrument {\n return Boolean(\n typeof data === 'object' &&\n data !== null &&\n 'accountNumber' in data &&\n 'accountType' in data &&\n 'shopperPermission' in data &&\n 'routingNumber' in data,\n );\n}\n\nexport function isIdealInstrument(paymentData: unknown): paymentData is WithIdealInstrument {\n return Boolean(typeof paymentData === 'object' && paymentData !== null && 'bic' in paymentData);\n}\n\nexport function isSepaInstrument(paymentData: unknown): paymentData is WithSepaInstrument {\n return Boolean(\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'iban' in paymentData &&\n 'firstName' in paymentData &&\n 'lastName' in paymentData &&\n 'shopperPermission' in paymentData,\n );\n}\n\nexport function isPayByBankInstrument(\n paymentData: unknown,\n): paymentData is WithPayByBankInstrument {\n return Boolean(\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'iban' in paymentData &&\n !('firstName' in paymentData) &&\n !('lastName' in paymentData) &&\n !('shopperPermission' in paymentData),\n );\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectAPMPaymentStrategy from './bluesnap-direct-apm-payment-strategy';\n\nconst createBlueSnapDirectAPMPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectAPMPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectAPMPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectAPMPaymentStrategy, [\n { gateway: 'bluesnapdirect' },\n]);\n","enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\n}\n\nexport default PaymentStatusTypes;\n","import { noop } from 'lodash';\n\nimport {\n CancellablePromise,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapV2StyleProps } from './bluesnapv2';\nimport {\n BlueSnapV2PaymentInitializeOptions,\n WithBlueSnapV2PaymentInitializeOptions,\n} from './bluesnapv2-payment-options';\n\nconst IFRAME_NAME = 'bluesnapv2_hosted_payment_page';\n\nexport default class BlueSnapV2PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapV2PaymentInitializeOptions;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions & WithBlueSnapV2PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onLoad, style } = this._initializeOptions;\n const frame = this._createIframe(IFRAME_NAME, style);\n const promise = new CancellablePromise(new Promise(noop));\n\n onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n await this._paymentIntegrationService.submitOrder(orderRequest, options);\n\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n shouldSaveInstrument: false,\n target: frame.name,\n promise: promise.promise,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async initialize(\n options?: PaymentInitializeOptions & WithBlueSnapV2PaymentInitializeOptions,\n ): Promise {\n this._initializeOptions = options && options.bluesnapv2;\n\n await Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createIframe(name: string, style?: BlueSnapV2StyleProps): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border ?? '';\n iframe.style.height = height ?? '';\n iframe.style.width = width ?? '';\n }\n\n return iframe;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapV2PaymentStrategy from './bluesnapv2-payment-strategy';\n\nconst createBluesnapV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BlueSnapV2PaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createBluesnapV2PaymentStrategy, [{ gateway: 'bluesnapv2' }]);\n","import { isObject } from 'lodash';\n\nimport { LineItemMap } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ExtraItemsData } from './extra-items-data';\n\ntype StorageFallback = Pick;\n\nconst ORDER_ITEMS_STORAGE_KEY = 'ORDER_ITEMS';\n\nfunction isExtraItemsData(itemsData: unknown): itemsData is ExtraItemsData {\n if (!isObject(itemsData)) {\n return false;\n }\n\n const hasNotExtraItems = Object.values(itemsData).some(\n (item) => !isObject(item) || !('brand' in item) || !('category' in item),\n );\n\n return Boolean(!hasNotExtraItems);\n}\n\nexport default class AnalyticsExtraItemsManager {\n constructor(private storage: StorageFallback) {}\n\n saveExtraItemsData(id: string, lineItems: LineItemMap): ExtraItemsData {\n const data = [...lineItems.physicalItems, ...lineItems.digitalItems].reduce(\n (result, item) => {\n result[item.productId] = {\n brand: item.brand ? item.brand : '',\n category: item.categoryNames ? item.categoryNames.join(', ') : '',\n };\n\n return result;\n },\n {},\n );\n\n try {\n this.storage.setItem(this.getStorageKey(id), JSON.stringify(data));\n\n return data;\n } catch (err) {\n return {};\n }\n }\n\n readExtraItemsData(id: string): ExtraItemsData | null {\n try {\n const item = this.storage.getItem(this.getStorageKey(id));\n\n if (!item) {\n return null;\n }\n\n const data: unknown = JSON.parse(item);\n\n return isExtraItemsData(data) ? data : null;\n } catch (err) {\n return null;\n }\n }\n\n clearExtraItemData(id: string): void {\n try {\n this.storage.removeItem(this.getStorageKey(id));\n } catch (err) {\n // silently ignore the failure\n }\n }\n\n private getStorageKey(id: string): string {\n return id ? `${ORDER_ITEMS_STORAGE_KEY}_${id}` : '';\n }\n}\n","import AnalyticsTrackerWindow from './analytics-tracker-window';\n\nexport function isAnalyticsTrackerWindow(window: Window): window is AnalyticsTrackerWindow {\n return Boolean(window.hasOwnProperty('analytics'));\n}\n","import { WithAccountCreation } from './payment';\n\nexport default function isWithAccountCreation(\n paymentData: unknown,\n): paymentData is WithAccountCreation {\n return (\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'shouldCreateAccount' in paymentData\n );\n}\n","import { PaymentErrorData, StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BoltError extends StandardError {\n body: { errors: PaymentErrorData[] };\n\n constructor(public errorCode: string) {\n super();\n\n this.name = 'BoltPaymentsFieldError';\n this.type = 'bolt_payments_field_error';\n this.body = { errors: [BoltError.getError(errorCode)] };\n }\n\n private static getError(errorCode: string): PaymentErrorData {\n switch (errorCode) {\n case '1000':\n case '2000':\n case '3000':\n return { code: 'invalid_number' };\n\n case '1001':\n case '2001':\n case '3001':\n return { code: 'invalid_expiry_date' };\n\n case '1002':\n case '2002':\n return { code: 'invalid_cvc' };\n\n case '1003':\n return { code: 'invalid_zip' };\n\n case '2003':\n return { code: 'incorrect_zip' };\n\n default:\n return { code: 'general_error' };\n }\n }\n}\n","import {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\nimport {\n InvalidArgumentError,\n isWithAccountCreation,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltEmbedded,\n BoltEmbeddedTokenize,\n BoltEmbededField,\n BoltPaymentMethod,\n BoltTransaction,\n} from './bolt';\nimport BoltError from './bolt-error';\nimport { WithBoltPaymentInitializeOptions } from './bolt-payment-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\nimport { isBoltPaymentData } from './is-bolt-payment-data';\n\nexport default class BoltPaymentStrategy implements PaymentStrategy {\n private boltClient?: BoltCheckout;\n private boltEmbedded?: BoltEmbedded;\n private embeddedField?: BoltEmbededField;\n private useBoltClient = false;\n private useBoltEmbedded = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBoltPaymentInitializeOptions,\n ): Promise {\n const { bolt, methodId } = options;\n const { containerId, onPaymentSelect, useBigCommerceCheckout } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!useBigCommerceCheckout) {\n // info: calling loadBoltClient method without providing any params is necessary for Bolt Full Checkout and Fraud Protection\n this.boltClient = await this.boltScriptLoader.loadBoltClient();\n\n return;\n }\n\n const paymentMethod: BoltPaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig, embeddedOneClickEnabled } =\n initializationData || {};\n const { testMode } = config;\n\n if (!publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.boltClient = await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.useBoltClient = !embeddedOneClickEnabled;\n this.useBoltEmbedded = !!embeddedOneClickEnabled;\n\n if (this.useBoltEmbedded) {\n if (!containerId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.containerId\" argument is not provided.',\n );\n }\n\n if (!onPaymentSelect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.onPaymentSelect\" argument is not provided.',\n );\n }\n\n this.boltEmbedded = await this.boltScriptLoader.loadBoltEmbedded(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.mountBoltEmbeddedField(containerId);\n onPaymentSelect(await this.hasBoltAccount());\n }\n }\n\n deinitialize(): Promise {\n this.embeddedField?.unmount();\n\n this.boltClient = undefined;\n this.boltEmbedded = undefined;\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n this.setExtraItemsForAnalytics();\n\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n let paymentPayload;\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentData || !isBoltPaymentData(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (this.useBoltClient) {\n paymentPayload = await this.getBoltClientPaymentPayload(methodId, paymentData, options);\n } else if (this.useBoltEmbedded) {\n paymentPayload = await this.getBoltEmbeddedPaymentPayload(methodId, paymentData);\n } else {\n paymentPayload = await this.getBoltFullCheckoutPaymentPayload(methodId, paymentData);\n }\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async getBoltClientPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n options?: PaymentRequestOptions,\n ): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(methodId, options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const orderToken = paymentMethod.clientToken;\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n const { shouldSaveInstrument } = paymentData;\n const boltClient = this.getBoltClientOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n\n if (!orderToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const boltTransaction: BoltTransaction = await new Promise((resolve, reject) => {\n const onSuccess = (transaction: BoltTransaction, callback: () => void) => {\n if (!transaction.reference) {\n reject(\n new PaymentMethodFailedError(\n 'Unable to proceed because transaction reference is unavailable. Please try again later.',\n ),\n );\n } else {\n resolve(transaction);\n }\n\n callback();\n };\n\n const onClose = () => {\n reject(new PaymentMethodCancelledError());\n };\n\n const callbacks = {\n success: onSuccess,\n close: onClose,\n };\n\n boltClient.configure({ orderToken }, {}, callbacks).open();\n });\n\n return {\n methodId,\n paymentData: {\n nonce: boltTransaction.reference,\n shouldSaveInstrument,\n },\n };\n }\n\n private async getBoltEmbeddedPaymentPayload(\n methodId: string,\n paymentData: WithAccountCreation,\n ): Promise {\n if (!isWithAccountCreation(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const tokenizeResult = this.validateTokenizeResultOrThrow(\n await this.embeddedField?.tokenize(),\n );\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: tokenizeResult.token,\n last_four_digits: tokenizeResult.last4,\n iin: tokenizeResult.bin,\n expiration_month: +tokenizeResult.expiration.split('-')[1],\n expiration_year: +tokenizeResult.expiration.split('-')[0],\n },\n provider_data: {\n create_account: !!paymentData.shouldCreateAccount,\n embedded_checkout: true,\n },\n },\n },\n };\n }\n\n private async getBoltFullCheckoutPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n ): Promise {\n await this.setBoltOrderId();\n\n const boltClient = this.getBoltClientOrThrow();\n const transactionReference = await boltClient.getTransactionReference();\n\n if (!transactionReference) {\n throw new PaymentMethodInvalidError();\n }\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n nonce: transactionReference,\n },\n };\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n if (!this.boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltClient;\n }\n\n private getBoltEmbeddedOrThrow() {\n if (!this.boltEmbedded) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltEmbedded;\n }\n\n private async hasBoltAccount(): Promise {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const email = customer?.email || billingAddress?.email || '';\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private async setBoltOrderId() {\n const order = this.paymentIntegrationService.getState().getOrderOrThrow();\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n await boltClient.setOrderId(order.orderId);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private mountBoltEmbeddedField(containerId: string) {\n const boltEmbedded = this.getBoltEmbeddedOrThrow();\n const styles = { backgroundColor: '#fff' };\n const embeddedField = boltEmbedded.create('payment_field', {\n styles,\n renderSeparateFields: true,\n });\n\n embeddedField.mount(`#${containerId}`);\n\n this.embeddedField = embeddedField;\n }\n\n private validateTokenizeResultOrThrow(\n tokenizeResult?: BoltEmbeddedTokenize | Error,\n ): BoltEmbeddedTokenize {\n if (!tokenizeResult) {\n throw new PaymentMethodInvalidError();\n }\n\n if (tokenizeResult instanceof Error) {\n throw new BoltError(tokenizeResult.message);\n }\n\n const { token, last4, bin, expiration } = tokenizeResult;\n const lastFourDigits = +last4;\n const iin = +bin;\n const expirationMonth = +`${expiration}`.split('-')[1];\n const expirationYear = +`${expiration}`.split('-')[0];\n\n if (\n !token ||\n Number.isNaN(lastFourDigits) ||\n Number.isNaN(iin) ||\n Number.isNaN(expirationMonth) ||\n Number.isNaN(expirationYear)\n ) {\n throw new PaymentArgumentInvalidError();\n }\n\n return tokenizeResult;\n }\n\n private setExtraItemsForAnalytics() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n const cart = state.getCartOrThrow();\n\n if (storeConfig.checkoutSettings.isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n const { id, lineItems } = cart;\n\n this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n }\n }\n}\n","import { isObject } from 'lodash';\n\nimport { isWithAccountCreation } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltPaymentData } from './bolt';\n\nexport function isBoltPaymentData(paymentData: unknown): paymentData is BoltPaymentData {\n return Boolean(\n isObject(paymentData) &&\n ('shouldSaveInstrument' in paymentData ||\n 'nonce' in paymentData ||\n isWithAccountCreation(paymentData)),\n );\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\nimport localStorageFallback from 'local-storage-fallback';\n\nimport { AnalyticsExtraItemsManager } from '@bigcommerce/checkout-sdk/analytics';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltPaymentStrategy from './bolt-payment-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltPaymentStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n new AnalyticsExtraItemsManager(localStorageFallback),\n );\n};\n\nexport default toResolvableModule(createBoltPaymentStrategy, [{ id: 'bolt' }]);\n","import {\n PaymentInstrumentPayload,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isUsBankAccountInstrumentLike(\n instrument?: PaymentInstrumentPayload,\n): instrument is WithBankAccountInstrument {\n if (!instrument) {\n return false;\n }\n\n return (\n 'accountNumber' in instrument &&\n 'routingNumber' in instrument &&\n 'ownershipType' in instrument &&\n 'accountType' in instrument\n );\n}\n","import {\n BraintreeInitializationData,\n BraintreeSdk,\n BraintreeUsBankAccount,\n BraintreeUsBankAccountDetails,\n isBraintreeError,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isUsBankAccountInstrumentLike from '../is-us-bank-account-instrument-like';\n\nimport { WithBraintreeAchPaymentInitializeOptions } from './braintree-ach-initialize-options';\n\nexport default class BraintreeAchPaymentStrategy implements PaymentStrategy {\n private usBankAccount?: BraintreeUsBankAccount;\n private getMandateText?: () => string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeAchPaymentInitializeOptions,\n ): Promise {\n const { methodId, braintreeach } = options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.getMandateText = braintreeach?.getMandateText;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n try {\n this.usBankAccount = await this.braintreeSdk.getUsBankAccount();\n } catch (error) {\n this.handleBraintreeError(error);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const isSubmittingWithVaultingInstrument = isVaultedInstrument(payment.paymentData || {});\n\n const nonce = isSubmittingWithVaultingInstrument\n ? await this.tokenizePaymentForVaultedInstrument(payment)\n : await this.tokenizePayment(payment);\n\n const submitPaymentPayload = isSubmittingWithVaultingInstrument\n ? await this.preparePaymentDataForVaultedInstrument(nonce, payment)\n : await this.preparePaymentData(nonce, payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n\n return Promise.resolve();\n }\n\n private async tokenizePayment({ paymentData }: OrderPaymentRequestBody): Promise {\n const usBankAccount = this.getUsBankAccountOrThrow();\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const mandateText = isVaultedInstrument(paymentData)\n ? 'The data are used for stored instrument verification'\n : typeof this.getMandateText === 'function' && this.getMandateText();\n\n if (!mandateText) {\n throw new InvalidArgumentError(\n 'Unable to proceed because getMandateText is not provided or returned undefined value.',\n );\n }\n\n try {\n const { nonce } = await usBankAccount.tokenize({\n bankDetails: this.getBankDetails(paymentData),\n mandateText,\n });\n\n return nonce;\n } catch (error) {\n this.handleBraintreeError(error);\n }\n }\n\n private async tokenizePaymentForVaultedInstrument(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n const state = this.paymentIntegrationService.getState();\n const { config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!config.isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n const shouldVerifyVaultingInstrument = isUsBankAccountInstrumentLike(paymentData);\n\n return shouldVerifyVaultingInstrument ? this.tokenizePayment(payment) : null;\n }\n\n private async preparePaymentData(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument, routingNumber, accountNumber } =\n paymentData;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId: deviceData,\n shouldSetAsDefaultInstrument,\n shouldSaveInstrument,\n formattedPayload: {\n tokenized_bank_account: {\n issuer: routingNumber,\n masked_account_number: accountNumber.substr(-4),\n token: nonce,\n },\n },\n },\n };\n }\n\n private async preparePaymentDataForVaultedInstrument(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n if (!isVaultedInstrument(paymentData) || !isHostedInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { instrumentId, shouldSetAsDefaultInstrument } = paymentData;\n\n return {\n methodId,\n paymentData: {\n deviceSessionId: deviceData,\n instrumentId,\n shouldSetAsDefaultInstrument,\n ...(nonce && { nonce }),\n },\n };\n }\n\n private getBankDetails(paymentData: WithBankAccountInstrument): BraintreeUsBankAccountDetails {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const ownershipType = paymentData.ownershipType.toLowerCase();\n const accountType = paymentData.accountType.toLowerCase();\n\n return {\n accountNumber: paymentData.accountNumber,\n routingNumber: paymentData.routingNumber,\n ownershipType,\n ...(ownershipType === 'personal'\n ? {\n firstName: paymentData.firstName,\n lastName: paymentData.lastName,\n }\n : {\n businessName: paymentData.businessName,\n }),\n accountType,\n billingAddress: {\n streetAddress: billingAddress.address1,\n extendedAddress: billingAddress.address2,\n locality: billingAddress.city,\n region: billingAddress.stateOrProvinceCode,\n postalCode: billingAddress.postalCode,\n },\n };\n }\n\n private getUsBankAccountOrThrow(): BraintreeUsBankAccount {\n if (!this.usBankAccount) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.usBankAccount;\n }\n\n private handleBraintreeError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n}\n","import { createBraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeAchPaymentStrategy from './braintree-ach-payment-strategy';\n\nconst createBraintreeAchPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BraintreeAchPaymentStrategy(paymentIntegrationService, createBraintreeSdk());\n};\n\nexport default toResolvableModule(createBraintreeAchPaymentStrategy, [{ id: 'braintreeach' }]);\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSdk from './braintree-sdk';\n\nconst createBraintreeSdk = () => {\n const braintreeScriptLoader = new BraintreeScriptLoader(getScriptLoader(), window);\n\n return new BraintreeSdk(braintreeScriptLoader);\n};\n\nexport default createBraintreeSdk;\n","import getOverlayStyle from './overlay-style';\n\nexport interface OverlayOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n hasCloseButton?: boolean;\n innerHtml?: HTMLElement | DocumentFragment;\n}\n\nexport interface OverlayShowOptions {\n onClick?(event: MouseEvent): void;\n onClickClose?(event: MouseEvent): void;\n}\n\nexport interface Elements {\n element: HTMLElement;\n mainElement: HTMLElement;\n closeElement?: HTMLElement;\n}\n\nexport default class Overlay {\n private _element: HTMLElement;\n private _mainElement: HTMLElement;\n private _closeElement?: HTMLElement;\n private _unregisterClick?: () => void;\n\n constructor(options?: OverlayOptions) {\n const { element, closeElement, mainElement } = this._createElements(options);\n\n this._element = element;\n this._closeElement = closeElement;\n this._mainElement = mainElement;\n }\n\n show(options?: OverlayShowOptions): void {\n if (this._mainElement.parentElement) {\n return;\n }\n\n this._registerClick(options);\n\n document.body.appendChild(this._mainElement);\n\n // Fade In\n setTimeout(() => (this._element.style.opacity = '1'));\n }\n\n remove(): void {\n if (!this._mainElement.parentElement) {\n return;\n }\n\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n this._removeAfterTransition();\n\n setTimeout(() => (this._element.style.opacity = '0'));\n }\n\n private _createElements(options?: OverlayOptions): Elements {\n const element = document.createElement('div');\n const {\n background = 'rgba(0, 0, 0, 0.8)',\n id = 'checkoutOverlay',\n transitionDuration = 400,\n hasCloseButton = false,\n innerHtml = null,\n } = options || {};\n let mainElement = element;\n let closeElement: HTMLElement | undefined;\n let classLayout: string | undefined;\n let classClose: string | undefined;\n let classOverlayText: string | undefined;\n\n if (id) {\n element.id = id;\n }\n\n if (innerHtml) {\n const overlayText = document.createElement('div');\n\n classOverlayText = `${id}--overlayText`;\n overlayText.className = classOverlayText;\n overlayText.appendChild(innerHtml);\n\n element.appendChild(overlayText);\n }\n\n if (hasCloseButton) {\n classClose = `${id}--close`;\n closeElement = document.createElement('div');\n closeElement.className = classClose;\n\n classLayout = `${id}--layout`;\n mainElement = document.createElement('div');\n mainElement.className = classLayout;\n\n mainElement.appendChild(element);\n mainElement.appendChild(closeElement);\n }\n\n mainElement.appendChild(\n getOverlayStyle({\n id,\n background,\n transitionDuration,\n classLayout,\n classOverlayText,\n classClose,\n }),\n );\n\n return { element, closeElement, mainElement };\n }\n\n private _addEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n if (!element || !onClick) {\n return;\n }\n\n element.addEventListener('click', onClick);\n }\n\n private _removeEventListener(\n element?: HTMLElement,\n onClick?: (event: MouseEvent) => void,\n ): void {\n if (!element || !onClick) {\n return;\n }\n\n element.removeEventListener('click', onClick);\n }\n\n private _registerClick(options?: OverlayShowOptions): void {\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n if (options) {\n const { onClick, onClickClose } = options;\n\n this._addEventListener(this._element, onClick);\n this._addEventListener(this._closeElement, onClickClose);\n\n this._unregisterClick = () => {\n this._removeEventListener(this._element, onClick);\n this._removeEventListener(this._closeElement, onClickClose);\n this._unregisterClick = undefined;\n };\n }\n }\n\n private _removeAfterTransition(): void {\n const handleTransition: (event: Event) => void = (event) => {\n // NOTE: `event` is not correctly typed in this version of TS\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n if ((event as TransitionEvent).propertyName !== 'opacity') {\n return;\n }\n\n if (this._mainElement.parentElement) {\n this._mainElement.remove();\n }\n\n this._element.removeEventListener('transitionend', handleTransition);\n };\n\n this._element.addEventListener('transitionend', handleTransition);\n }\n}\n","interface OverlayStyleOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n classLayout?: string;\n classOverlayText?: string;\n classClose?: string;\n}\n\nexport default function getOverlayStyle(options: OverlayStyleOptions): HTMLElement {\n const { id, background, transitionDuration, classLayout, classOverlayText, classClose } =\n options;\n const styles = document.createElement('style');\n const addClassLayout = classLayout ? `, .${classLayout}` : '';\n\n styles.id = `${id}--styles`;\n styles.type = 'text/css';\n styles.innerText = `\n #${id}${addClassLayout} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${id} {\n transition: opacity ${transitionDuration}ms ease-out;\n background: ${background};\n opacity: 0;\n }\n `;\n\n if (classOverlayText) {\n styles.innerText += `\n #${id} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${id} .${classOverlayText} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `;\n }\n\n if (classClose) {\n styles.innerText += `\n #${id} {\n opacity: 1;\n }\n .${classLayout} .${classClose} {\n position: fixed;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n cursor: pointer;\n z-index: 3147483647;\n }\n .${classLayout} .${classClose}::after, .${classLayout} .${classClose}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${classLayout} .${classClose}::after {\n transform: rotate(-45deg);\n }\n .${classLayout} .${classClose}::before {\n transform: rotate(45deg);\n }\n `;\n }\n\n return styles;\n}\n","import {\n LoadingIndicatorContainerStyles,\n LoadingIndicatorStyles,\n} from './loading-indicator-styles';\n\nconst DEFAULT_STYLES: LoadingIndicatorStyles = {\n size: 70,\n color: '#d9d9d9',\n backgroundColor: '#ffffff',\n};\n\nconst ROTATION_ANIMATION = 'embedded-checkout-loading-indicator-rotation';\n\ninterface LoadingIndicatorOptions {\n styles?: LoadingIndicatorStyles;\n containerStyles?: LoadingIndicatorContainerStyles;\n}\n\nexport default class LoadingIndicator {\n private container: HTMLElement;\n private indicator: HTMLElement;\n private styles: LoadingIndicatorStyles;\n private containerStyles: LoadingIndicatorContainerStyles;\n\n constructor(options?: LoadingIndicatorOptions) {\n this.styles = { ...DEFAULT_STYLES, ...(options && options.styles) };\n this.containerStyles = { ...(options && options.containerStyles) };\n\n this.defineAnimation();\n\n this.container = this.buildContainer();\n this.indicator = this.buildIndicator();\n\n this.container.appendChild(this.indicator);\n }\n\n show(parentId?: string): void {\n if (parentId) {\n const parent = document.getElementById(parentId);\n\n if (!parent) {\n throw new Error(\n 'Unable to attach the loading indicator because the parent ID is not valid.',\n );\n }\n\n parent.appendChild(this.container);\n }\n\n this.container.style.visibility = 'visible';\n this.container.style.opacity = '1';\n }\n\n hide(): void {\n const handleTransitionEnd = () => {\n this.container.style.visibility = 'hidden';\n\n this.container.removeEventListener('transitionend', handleTransitionEnd);\n };\n\n this.container.addEventListener('transitionend', handleTransitionEnd);\n\n this.container.style.opacity = '0';\n }\n\n private buildContainer(): HTMLElement {\n const container = document.createElement('div');\n\n container.style.display = 'block';\n container.style.bottom = '0';\n container.style.left = '0';\n container.style.height = '100%';\n container.style.width = '100%';\n container.style.position = 'absolute';\n container.style.right = '0';\n container.style.top = '0';\n container.style.transition = 'all 250ms ease-out';\n container.style.opacity = '0';\n\n this.setStyleAttribute(container, this.containerStyles);\n\n return container;\n }\n\n private buildIndicator(): HTMLElement {\n const indicator = document.createElement('div');\n\n indicator.style.display = 'block';\n indicator.style.width = `${this.styles.size}px`;\n indicator.style.height = `${this.styles.size}px`;\n indicator.style.borderRadius = `${this.styles.size}px`;\n indicator.style.border = 'solid 1px';\n indicator.style.borderColor = `${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`;\n indicator.style.margin = '0 auto';\n indicator.style.position = 'absolute';\n indicator.style.left = '0';\n indicator.style.right = '0';\n indicator.style.top = '50%';\n indicator.style.transform = 'translateY(-50%) rotate(0deg)';\n indicator.style.transformStyle = 'preserve-3d';\n indicator.style.animation = `${ROTATION_ANIMATION} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`;\n\n return indicator;\n }\n\n private setStyleAttribute(element: HTMLElement, attrs: { [key: string]: string }): void {\n Object.keys(attrs).forEach((k) => {\n element.style.setProperty(k, attrs[k]);\n });\n }\n\n private defineAnimation(): void {\n // In order to define CSS animation, we need to insert a stylesheet into the host frame.\n // We only have to do it once.\n if (document.getElementById(ROTATION_ANIMATION)) {\n return;\n }\n\n const style = document.createElement('style');\n\n style.id = ROTATION_ANIMATION;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n document.head?.appendChild(style);\n\n if (style.sheet instanceof CSSStyleSheet) {\n // We need to provide the 2nd parameter for IE11, even though it is\n // 0 by default for all other browsers.\n style.sheet.insertRule(\n `\n @keyframes ${ROTATION_ANIMATION} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,\n 0,\n );\n }\n }\n}\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import { BraintreeError } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nexport default function isBraintreeError(\n error: BraintreeError | Error | unknown,\n): error is BraintreeError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n (error as BraintreeError).name === 'BraintreeError'\n );\n}\n","import { BraintreeShippingAddressOverride } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { Address } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","import {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n PaypalAuthorizeData,\n PaypalButtonRender,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n FormattedPayload,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isHostedVaultedInstrument,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n PaypalInstrument,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport isBraintreeError from '../is-braintree-error';\nimport isBraintreePaypalProviderError from '../is-braintree-paypal-provider-error';\nimport mapToBraintreeShippingAddressOverride from '../map-to-braintree-shipping-address-override';\n\nimport {\n BraintreePaypalPaymentInitializeOptions,\n WithBraintreePaypalPaymentInitializeOptions,\n} from './braintree-paypal-payment-initialize-options';\n\nexport default class BraintreePaypalPaymentStrategy implements PaymentStrategy {\n private paymentMethod?: PaymentMethod;\n private braintreeHostWindow: BraintreeHostWindow = window;\n private braintree?: BraintreePaypalPaymentInitializeOptions;\n private braintreeTokenizePayload?: BraintreeTokenizePayload;\n private paypalButtonRender?: PaypalButtonRender;\n private loadingIndicatorContainer?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalPaymentInitializeOptions,\n ) {\n const { braintree: braintreeOptions, methodId } = options;\n\n this.braintree = braintreeOptions;\n\n if (!this.paymentMethod || !this.paymentMethod.nonce) {\n this.paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n }\n\n if (this.paymentMethod.clientToken && braintreeOptions?.bannerContainerId) {\n await this.loadPaypal();\n\n return this.loadPaypalCheckoutInstance();\n }\n\n if (this.paymentMethod.clientToken) {\n return this.loadPaypal();\n }\n\n const state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n this.paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (braintreeOptions?.bannerContainerId) {\n return this.loadPaypalCheckoutInstance();\n }\n\n if (!this.paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this.loadPaypal();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n const { onError } = this.braintree || {};\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const shouldHandleInstrumentDeclinedError =\n features && features['PAYPAL-3521.handling_declined_error_braintree'];\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this.preparePaymentData(payment, order.useStoreCredit);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentData);\n } catch (error) {\n if (this.isProviderError(error) && shouldHandleInstrumentDeclinedError) {\n await this.loadPaypal();\n\n this.paypalButtonRender?.close();\n\n await this.loadPaypalCheckoutInstance();\n\n await new Promise((_resolve, reject) => {\n if (onError && typeof onError === 'function') {\n onError(new Error('INSTRUMENT_DECLINED'));\n }\n\n reject();\n });\n }\n\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.braintreeTokenizePayload = undefined;\n\n this.paypalButtonRender?.close();\n\n return this.braintreeIntegrationService.teardown();\n }\n\n private async preparePaymentData(\n payment: OrderPaymentRequestBody,\n useStoreCredit?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n const grandTotal = state.getOutstandingBalance(useStoreCredit);\n const config = state.getStoreConfig();\n\n if (!grandTotal) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this.paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n currency,\n storeProfile: { storeLanguage },\n } = config;\n const {\n nonce,\n config: { isVaultingEnabled },\n } = this.paymentMethod;\n const { methodId, paymentData = {} } = payment;\n\n const token = this.braintreeTokenizePayload?.nonce || nonce;\n\n if (token) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n this.paymentMethod = state.getPaymentMethod(methodId);\n\n return {\n ...payment,\n paymentData: this.formattedPayload(token),\n };\n }\n\n if (isVaultedInstrument(paymentData) || isHostedVaultedInstrument(paymentData)) {\n if (!isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n return Promise.resolve(payment);\n }\n\n if (!isHostedInstrumentLike(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = paymentData;\n\n if (shouldSaveInstrument && !isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but shouldSaveInstrument is set to true',\n );\n }\n\n const shippingAddress = state.getShippingAddress();\n\n const shippingAddressOverride = shippingAddress\n ? mapToBraintreeShippingAddressOverride(shippingAddress)\n : undefined;\n\n return Promise.all([\n this.braintreeIntegrationService.paypal({\n amount: grandTotal,\n locale: storeLanguage,\n currency: currency.code,\n offerCredit: this.paymentMethod.id === 'braintreepaypalcredit',\n shippingAddressOverride,\n shouldSaveInstrument: shouldSaveInstrument || false,\n shippingAddressEditable: false,\n }),\n this.braintreeIntegrationService.getSessionId(),\n ]).then(([{ nonce, details } = {} as any, sessionId]) => ({\n ...payment,\n paymentData: this.formattedPayload(\n nonce,\n details && details.email,\n sessionId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n ),\n }));\n }\n\n private formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n vaultPaymentInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: vaultPaymentInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private async loadPaypalCheckoutInstance() {\n const { clientToken, initializationData } = this.paymentMethod || {};\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n\n const currencyCode = this.paymentIntegrationService.getState().getCartOrThrow()\n .currency.code;\n\n const paypalCheckoutConfig: Partial = {\n currency: currencyCode,\n intent: initializationData?.intent,\n isCreditEnabled: initializationData?.isCreditEnabled,\n };\n\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutConfig,\n (braintreePaypalCheckout) => {\n if (initializationData?.enableCheckoutPaywallBanner) {\n this.renderPayPalMessages();\n }\n\n this.renderPayPalButton(braintreePaypalCheckout);\n },\n this.handleError,\n );\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private renderPayPalButton(braintreePaypalCheckout: BraintreePaypalCheckout) {\n const { onPaymentError, submitForm, onRenderButton, containerId, onError } =\n this.braintree || {};\n\n if (!containerId) {\n return;\n }\n\n if (!this.paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.loadingIndicatorContainer = containerId.split('#')[1];\n\n const {\n id,\n config: { testMode },\n } = this.paymentMethod;\n\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n this.paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n onClick: () => {\n this.toggleLoadingIndicator(true);\n },\n createOrder: () => this.setupPayment(braintreePaypalCheckout, id, onPaymentError),\n onApprove: async (authorizeData: PaypalAuthorizeData) => {\n this.braintreeTokenizePayload = await this.tokenizePaymentOrThrow(\n authorizeData,\n braintreePaypalCheckout,\n );\n\n if (submitForm && typeof submitForm === 'function') {\n submitForm();\n }\n },\n onCancel: () => {\n this.toggleLoadingIndicator(false);\n },\n onError: (error: Error) => {\n this.toggleLoadingIndicator(false);\n\n onError?.(error);\n },\n });\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n if (this.paypalButtonRender.isEligible()) {\n this.paypalButtonRender.render(`${containerId}`);\n }\n } else {\n this.removeElement(containerId.split('#')[1]);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n method: string,\n onPaymentError: BraintreePaypalPaymentInitializeOptions['onPaymentError'],\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n try {\n const customer = state.getCustomer();\n\n const paymentMethod: PaymentMethod = state.getPaymentMethodOrThrow(method);\n\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currencyCode = state.getStoreConfigOrThrow().currency.code;\n\n const shippingAddress = state.getShippingAddress();\n\n const address = shippingAddress || customer?.addresses[0];\n\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData.intent,\n });\n } catch (error) {\n if (onPaymentError && (isBraintreeError(error) || error instanceof StandardError)) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePaymentOrThrow(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n return await braintreePaypalCheckout.tokenizePayment(authorizeData);\n } catch (error) {\n if (onError && (isBraintreeError(error) || error instanceof StandardError)) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private renderPayPalMessages() {\n const { bannerContainerId } = this.braintree || {};\n\n if (\n this.braintreeHostWindow.paypal &&\n bannerContainerId &&\n Boolean(document.getElementById(bannerContainerId))\n ) {\n const state = this.paymentIntegrationService.getState();\n const checkout = state.getCheckout();\n const billingAddress = state.getBillingAddressOrThrow();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n this.braintreeHostWindow.paypal\n .Messages({\n amount: checkout.subtotal,\n buyerCountry: billingAddress.countryCode,\n placement: 'payment',\n style: {\n layout: 'text',\n logo: {\n type: 'inline',\n },\n },\n })\n .render(`#${bannerContainerId}`);\n }\n }\n\n private async loadPaypal() {\n const { clientToken, initializationData } = this.paymentMethod || {};\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(clientToken);\n\n await this.braintreeIntegrationService.getPaypal();\n } catch (error) {\n this.handleError(error);\n }\n\n return Promise.resolve();\n }\n\n private handleError(error: BraintreeError | Error | unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private isProviderError(error: unknown): boolean {\n if (isBraintreePaypalProviderError(error)) {\n const paypalProviderError = error?.errors?.filter((e) => e.provider_error) || [];\n\n return paypalProviderError[0]?.provider_error?.code === '2046';\n }\n\n return false;\n }\n\n private removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","export interface ProviderError extends Error {\n errors?: ErrorElement[];\n status?: string;\n three_ds_result?: {\n acs_url: unknown;\n payer_auth_request: unknown;\n merchant_data: unknown;\n callback_url: unknown;\n };\n}\n\nexport interface ErrorElement {\n code: string;\n message: string;\n provider_error?: {\n code: string;\n };\n}\n\nexport default function isBraintreePaypalProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator, Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport { LOADING_INDICATOR_STYLES } from '../braintree-paypal-constants';\n\nimport BraintreePaypalPaymentStrategy from './braintree-paypal-payment-strategy';\n\nconst createBraintreePaypalPaymentStrategy: PaymentStrategyFactory<\n BraintreePaypalPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const overlay = new Overlay();\n\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n overlay,\n );\n\n return new BraintreePaypalPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalPaymentStrategy, [\n { id: 'braintreepaypal' },\n { id: 'braintreepaypalcredit' },\n]);\n","import {\n BraintreeInitializationData,\n BraintreeLocalPayment,\n BraintreeLocalPaymentConfig,\n BraintreeLocalPaymentMethodRedirectAction,\n BraintreeLocalPaymentsPayload,\n BraintreeLPMPaymentStartData,\n BraintreeLPMStartPaymentError,\n BraintreeOrderSavedResponse,\n BraintreeRedirectError,\n BraintreeSdk,\n NonInstantLocalPaymentMethods,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrumentMeta,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport {\n BraintreeLocalMethodsPaymentInitializeOptions,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-payment-initialize-options';\n\nexport default class BraintreeLocalMethodsPaymentStrategy implements PaymentStrategy {\n private braintreelocalmethods?: BraintreeLocalMethodsPaymentInitializeOptions;\n private braintreeLocalPayment?: BraintreeLocalPayment;\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private isLPMsUpdateExperimentEnabled = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeSdk: BraintreeSdk,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!braintreelocalmethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreelocalmethods\" argument is not provided.`,\n );\n }\n\n this.braintreelocalmethods = braintreelocalmethods;\n this.loadingIndicatorContainer = braintreelocalmethods.container.split('#')[1];\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(gatewayId);\n const { clientToken, config, initializationData } = paymentMethod;\n\n this.isLPMsUpdateExperimentEnabled =\n state.getStoreConfigOrThrow().checkoutSettings.features[\n 'PAYPAL-4853.add_new_payment_flow_for_braintree_lpms'\n ] || false;\n\n if (!clientToken || !initializationData || !config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeSdk.initialize(clientToken);\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n this.braintreeLocalPayment = await this.braintreeSdk.getBraintreeLocalPayment(\n config.merchantId,\n );\n }\n } catch (error: unknown) {\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.toggleLoadingIndicator(false);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n this.toggleLoadingIndicator(true);\n\n if (this.isNonInstantPaymentMethod(methodId)) {\n await this.executeWithNotInstantLPM(methodId);\n } else {\n await this.executeWithInstantLPM(methodId, order, options);\n }\n }\n\n private async executeWithNotInstantLPM(methodId: string): Promise {\n try {\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n\n await this.paymentIntegrationService.submitOrder();\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n },\n },\n });\n } catch (error: unknown) {\n if (this.isBraintreeRedirectError(error)) {\n const redirectUrl = error.body.additional_action_required.data.redirect_url;\n\n return new Promise((_, reject) => {\n window.location.replace(redirectUrl);\n\n this.toggleLoadingIndicator(false);\n\n reject();\n });\n }\n\n this.handleError(error);\n\n return Promise.reject(error);\n }\n }\n\n private async executeWithInstantLPM(\n methodId: string,\n order: Omit,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!this.braintreeLocalPayment) {\n throw new PaymentMethodInvalidError();\n }\n\n await new Promise((resolve, reject): void => {\n this.braintreeLocalPayment?.startPayment(\n this.getInstantLPMConfig(methodId, order, options),\n this.getInstantLPMCallback(resolve, reject, methodId, order, options),\n );\n });\n }\n\n private async getLPMsBasicPaymentData(): Promise {\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n\n return { deviceSessionId: deviceData };\n }\n\n private getInstantLPMConfig(\n methodId: string,\n order: Omit,\n options?: RequestOptions,\n ): BraintreeLocalPaymentConfig {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const billing = state.getBillingAddressOrThrow();\n const { firstName, lastName, countryCode } = billing;\n const { currency, email, lineItems } = cart;\n const isShippingRequired = lineItems.physicalItems.length > 0;\n const grandTotal = state.getCheckoutOrThrow().outstandingBalance;\n\n return {\n paymentType: methodId,\n amount: grandTotal,\n fallback: {\n url: 'url-placeholder',\n buttonText: 'button placeholder',\n },\n currencyCode: currency.code,\n shippingAddressRequired: isShippingRequired,\n email,\n givenName: firstName,\n surname: lastName,\n address: {\n countryCode,\n },\n onPaymentStart: async (data: BraintreeLPMPaymentStartData, start: () => void) => {\n if (!this.isLPMsUpdateExperimentEnabled) {\n this.orderId = data.paymentId;\n\n start();\n\n return;\n }\n\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n const paymentData = {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n [`${methodId}_account`]: {\n order_id: data.paymentId,\n },\n },\n };\n\n try {\n // Submit order and payment should be performed to pass order_id to the backend\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n });\n } catch (error: unknown) {\n if (\n this.isBraintreeOrderSavedResponse(error) &&\n error.body.additional_action_required.data.order_id_saved_successfully\n ) {\n // Start method call initiates the popup\n start();\n\n return;\n }\n\n throw error;\n }\n },\n };\n }\n\n private getInstantLPMCallback(\n resolve: (value: unknown) => void,\n reject: (reason?: unknown) => void,\n methodId: string,\n order: Omit,\n options?: RequestOptions,\n ) {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n\n return async (\n startPaymentError: BraintreeLPMStartPaymentError | undefined,\n payloadData: BraintreeLocalPaymentsPayload,\n ) => {\n if (startPaymentError) {\n if (startPaymentError.code === 'LOCAL_PAYMENT_WINDOW_CLOSED') {\n this.toggleLoadingIndicator(false);\n\n return reject();\n }\n\n this.toggleLoadingIndicator(false);\n\n return reject(new PaymentMethodInvalidError());\n }\n\n const basicPaymentData = await this.getLPMsBasicPaymentData();\n const paymentData = {\n ...basicPaymentData,\n formattedPayload: {\n method: methodId,\n [`${methodId}_account`]: {\n email: cart.email,\n token: payloadData.nonce,\n ...(!this.isLPMsUpdateExperimentEnabled ? { order_id: this.orderId } : {}),\n },\n },\n };\n\n try {\n if (!this.isLPMsUpdateExperimentEnabled) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData,\n });\n\n return resolve(undefined);\n } catch (error: unknown) {\n this.handleError(error);\n\n return reject(error);\n }\n };\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n private handleError(error: unknown) {\n const { onError } = this.braintreelocalmethods || {};\n\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantLocalPaymentMethods;\n }\n\n private isBraintreeRedirectError(error: unknown): error is BraintreeRedirectError {\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n\n const { body }: Partial = error;\n\n if (!body) {\n return false;\n }\n\n return !!body.additional_action_required?.data.redirect_url;\n }\n\n private isBraintreeOrderSavedResponse(\n response: unknown,\n ): response is BraintreeOrderSavedResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const { body }: Partial = response;\n\n if (!body) {\n return false;\n }\n\n return body.additional_action_required?.data.hasOwnProperty('order_id_saved_successfully');\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeSdk,\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n};\n\nexport default toResolvableModule(createBraintreeLocalMethodsPaymentStrategy, [\n { gateway: 'braintreelocalmethods' },\n]);\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isBraintreeAcceleratedCheckoutCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneCardComponent,\n BraintreeFastlaneCardComponentOptions,\n BraintreeInitializationData,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CardInstrument,\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport { WithBraintreeFastlanePaymentInitializeOptions } from './braintree-fastlane-payment-initialize-options';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nexport default class BraintreeFastlanePaymentStrategy implements PaymentStrategy {\n private braintreeCardComponent?: BraintreeFastlaneCardComponent;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeFastlaneUtils: BraintreeFastlaneUtils,\n private browserStorage: BrowserStorage,\n ) {}\n\n /**\n *\n * Default methods\n *\n */\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeFastlanePaymentInitializeOptions,\n ): Promise {\n const { methodId, braintreefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreefastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane\" argument is not provided.',\n );\n }\n\n if (!braintreefastlane.onInit || typeof braintreefastlane.onInit !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (!braintreefastlane.onChange || typeof braintreefastlane.onChange !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreefastlane.onChange\" argument is not provided or it is not a function.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, isFastlaneStylingEnabled } = paymentMethod.initializationData || {};\n\n const paypalFastlaneStyleSettings = isFastlaneStylingEnabled\n ? paymentMethod.initializationData?.fastlaneStyles\n : undefined;\n\n if (!clientToken) {\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStyleSettings,\n braintreefastlane.styles,\n );\n\n await this.braintreeFastlaneUtils.initializeBraintreeFastlaneOrThrow(\n methodId,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.braintreeFastlaneUtils.runPayPalAuthenticationFlowOrThrow();\n }\n\n await this.initializeCardComponent();\n\n braintreefastlane.onInit((container) => this.renderBraintreeCardComponent(container));\n braintreefastlane.onChange(() => this.handleBraintreeStoredInstrumentChange(methodId));\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentPayload = await this.preparePaymentPayload(payment.methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n\n this.browserStorage.removeItem('sessionId');\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.braintreeCardComponent = undefined;\n\n return Promise.resolve();\n }\n\n /**\n *\n * Braintree Fastlane Component rendering method\n *\n */\n private async initializeCardComponent() {\n const state = this.paymentIntegrationService.getState();\n const { phone, firstName, lastName } = state.getBillingAddressOrThrow();\n const fullName = `${firstName} ${lastName}`;\n\n const cardComponentOptions: BraintreeFastlaneCardComponentOptions = {\n styles: {},\n fields: {\n cardholderName: {\n prefill: fullName,\n enabled: true,\n },\n ...(phone && {\n phoneNumber: {\n prefill: phone,\n },\n }),\n },\n };\n\n const paypalPaymentComponent =\n this.braintreeFastlaneUtils.getBraintreeFastlaneComponentOrThrow();\n\n this.braintreeCardComponent = await paypalPaymentComponent(cardComponentOptions);\n }\n\n private renderBraintreeCardComponent(container?: string) {\n const braintreeCardComponent = this.getBraintreeCardComponentOrThrow();\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n braintreeCardComponent.render(container);\n }\n\n /**\n *\n * Payment Payload preparation methods\n *\n */\n private async preparePaymentPayload(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`;\n\n const paypalInstrument = this.getPayPalInstruments()[0];\n\n const deviceSessionId = await this.braintreeFastlaneUtils.getDeviceSessionId();\n\n if (paypalInstrument) {\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n paypal_fastlane_token: {\n token: paypalInstrument.bigpayToken,\n },\n },\n },\n };\n }\n\n const { getPaymentToken } = this.getBraintreeCardComponentOrThrow();\n\n const { id } = await getPaymentToken({\n name: { fullName },\n billingAddress: this.mapToPayPalAddress(billingAddress),\n });\n\n return {\n methodId,\n paymentData: {\n deviceSessionId,\n nonce: id,\n },\n };\n }\n\n /**\n *\n * Mapper methods\n *\n */\n private mapToPayPalAddress(address?: Address): BraintreeFastlaneAddress {\n return {\n streetAddress: address?.address1 || '',\n locality: address?.city || '',\n region: address?.stateOrProvinceCode || address?.stateOrProvince || '',\n postalCode: address?.postalCode || '',\n countryCodeAlpha2: address?.countryCode || '',\n };\n }\n\n /**\n *\n * Other methods\n *\n */\n private shouldRunAuthenticationFlow(): boolean {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const paypalFastlaneSessionId = this.browserStorage.getItem('sessionId');\n\n if (\n !customer.isGuest ||\n braintreePaymentProviderCustomer?.authenticationState ===\n BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return (\n !braintreePaymentProviderCustomer?.authenticationState &&\n paypalFastlaneSessionId === cart.id\n );\n }\n\n private getBraintreeCardComponentOrThrow() {\n if (!this.braintreeCardComponent) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeCardComponent;\n }\n\n private getPayPalInstruments(): CardInstrument[] {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return braintreePaymentProviderCustomer.instruments || [];\n }\n\n /**\n *\n * Braintree Fastlane instrument change\n *\n */\n private async handleBraintreeStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.braintreeFastlaneUtils.getBraintreeFastlaneOrThrow();\n\n const { selectionChanged, selectedCard } = await paypalAxoSdk.profile.showCardSelector();\n\n if (selectionChanged) {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const braintreeFastlaneCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const selectedInstruments = this.braintreeFastlaneUtils.mapPayPalToBcInstrument(\n methodId,\n [selectedCard],\n );\n\n if (selectedInstruments && selectedInstruments.length > 0) {\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n ...braintreeFastlaneCustomer,\n instruments: [...selectedInstruments],\n });\n\n return selectedInstruments[0];\n }\n }\n\n return undefined;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport BraintreeFastlanePaymentStrategy from './braintree-fastlane-payment-strategy';\nimport BraintreeFastlaneUtils from './braintree-fastlane-utils';\n\nconst createBraintreeFastlanePaymentStrategy: PaymentStrategyFactory<\n BraintreeFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n const browserStorage = new BrowserStorage('paypalFastlane');\n\n const braintreeFastlaneUtils = new BraintreeFastlaneUtils(\n paymentIntegrationService,\n braintreeIntegrationService,\n browserStorage,\n );\n\n return new BraintreeFastlanePaymentStrategy(\n paymentIntegrationService,\n braintreeFastlaneUtils,\n browserStorage,\n );\n};\n\nexport default toResolvableModule(createBraintreeFastlanePaymentStrategy, [\n { id: 'braintreeacceleratedcheckout' },\n]);\n","import { isNil, values } from 'lodash';\n\nimport {\n HostedForm,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCreditCardPaymentInitializeOptions } from './credit-card-payment-initialize-options';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(protected _paymentIntegrationService: PaymentIntegrationService) {}\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n initialize(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve();\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const state = this._paymentIntegrationService.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n state.getStoreConfigOrThrow();\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._paymentIntegrationService.createHostedForm(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return Promise.resolve();\n });\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await form.validate().then(() => form.submit(payment));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { PaymentMethod } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface AdditionalActionRequired {\n type: AdditionalActionType;\n data: AdditionalRedirectData;\n}\n\nexport interface AdditionalRedirectData {\n redirect_url: string;\n transaction_id?: string;\n}\n\nexport enum AdditionalActionType {\n OffsiteRedirect = 'offsite_redirect',\n}\n\nexport function getCheckoutcom(): PaymentMethod {\n return {\n id: 'checkoutcom',\n logoUrl: '',\n method: 'checkoutcom',\n supportedCards: [],\n config: {\n displayName: 'Checkout.com',\n merchantId: '',\n testMode: true,\n },\n initializationData: {\n checkoutcomkey: 'key',\n },\n type: 'PAYMENT_TYPE_API',\n clientToken: 'clientToken',\n };\n}\n\nexport interface WithDocumentInstrument {\n ccDocument: string;\n}\n\nexport interface WithCheckoutcomSEPAInstrument {\n iban: string;\n bic: string;\n}\n\nexport interface WithCheckoutcomFawryInstrument {\n customerMobile: string;\n customerEmail: string;\n}\n","import { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, AdditionalActionType } from './checkoutcom';\n\nexport default class CheckoutComCustomPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(protected paymentIntegrationService: PaymentIntegrationService) {\n super(paymentIntegrationService);\n }\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this.paymentIntegrationService.submitOrder(order, options);\n await form.submit(payment);\n } catch (error) {\n return this._processResponse(error);\n }\n\n this.paymentIntegrationService.loadCurrentOrder();\n }\n\n protected _processResponse(error: unknown): Promise {\n if (!isRequestError(error)) {\n return Promise.reject(error);\n }\n\n const additionalActionRequired: AdditionalActionRequired =\n error.body.additional_action_required;\n\n // TODO validate all possible responses and perform respective additional actions\n if (\n additionalActionRequired &&\n additionalActionRequired.type === AdditionalActionType.OffsiteRedirect\n ) {\n return this._performRedirect(additionalActionRequired);\n }\n\n return Promise.reject(error);\n }\n\n private _performRedirect(additionalActionRequired: AdditionalActionRequired): Promise {\n return new Promise(() => {\n window.location.replace(additionalActionRequired.data.redirect_url);\n });\n }\n}\n","import {\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCheckoutcomFawryInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_FAWRY_PAYMENT_METHOD = 'fawry';\n\nexport default class CheckoutComFawryPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomFawryInstrument | undefined {\n if (\n CHECKOUTCOM_FAWRY_PAYMENT_METHOD === methodId &&\n 'customerMobile' in paymentData &&\n 'customerEmail' in paymentData\n ) {\n const fawryPaymentData = paymentData as {\n customerMobile: string;\n customerEmail: string;\n };\n\n return {\n customerMobile: fawryPaymentData.customerMobile,\n customerEmail: fawryPaymentData.customerEmail,\n };\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComFawryPaymentStrategy from './checkoutcom-fawry-payment-strategy';\n\nconst createCheckoutComFawryPaymentStrategy: PaymentStrategyFactory<\n CheckoutComFawryPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComFawryPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComFawryPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'fawry' },\n]);\n","import { some } from 'lodash';\n\nimport { isRequestError, RequestError } from './';\n\nexport default function isThreeDSecureRequiredError(error: unknown): error is RequestError {\n return isRequestError(error) && some(error.body.errors, { code: 'three_d_secure_required' });\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isThreeDSecureRequiredError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CheckoutComCreditCardPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n protected formPoster: FormPoster,\n ) {\n super(paymentIntegrationService);\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (isThreeDSecureRequiredError(error)) {\n return this._handleThreeDSecure(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this.paymentIntegrationService.submitOrder(order, options);\n await form.submit(payment);\n } catch (error) {\n if (isThreeDSecureRequiredError(error)) {\n return this._handleThreeDSecure(error);\n }\n\n return Promise.reject(error);\n }\n\n this.paymentIntegrationService.loadCurrentOrder();\n }\n\n private _handleThreeDSecure(error: RequestError): Promise {\n const { acs_url, payer_auth_request, callback_url, merchant_data } =\n error.body.three_ds_result;\n\n return new Promise(() =>\n this.formPoster.postForm(acs_url, {\n PaReq: payer_auth_request || null,\n TermUrl: callback_url || null,\n MD: merchant_data || null,\n }),\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCreditCardPaymentStrategy from './checkoutcom-credit-card-payment-strategy';\n\nconst createCheckoutComCreditCardPaymentStrategy: PaymentStrategyFactory<\n CheckoutComCreditCardPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComCreditCardPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createCheckoutComCreditCardPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'credit_card' },\n { gateway: 'checkoutcom', id: 'card' },\n]);\n","import {\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCheckoutcomSEPAInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_SEPA_PAYMENT_METHOD = 'sepa';\n\nexport default class CheckoutComSEPAPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomSEPAInstrument {\n const formattedPayload: WithCheckoutcomSEPAInstrument = { iban: '', bic: '' };\n const { iban, bic } =\n 'iban' in paymentData && 'bic' in paymentData ? paymentData : formattedPayload;\n\n if (methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD && document) {\n formattedPayload.iban = iban;\n formattedPayload.bic = bic;\n }\n\n return formattedPayload;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComSepaPaymentStrategy from './checkoutcom-sepa-payment-strategy';\n\nconst createCheckoutComSepaPaymentStrategy: PaymentStrategyFactory<\n CheckoutComSepaPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComSepaPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComSepaPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'sepa' },\n]);\n","import {\n CreditCardInstrument,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n WithIdealInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_IDEAL_PAYMENT_METHOD = 'ideal';\n\nexport default class CheckoutComiDealPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument | (CreditCardInstrument & WithIdealInstrument),\n ): WithIdealInstrument | undefined {\n if (CHECKOUTCOM_IDEAL_PAYMENT_METHOD === methodId && 'bic' in paymentData) {\n return { bic: paymentData.bic };\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComiDealPaymentStrategy from './checkoutcom-ideal-payment-strategy';\n\nconst createCheckoutComiDealPaymentStrategy: PaymentStrategyFactory<\n CheckoutComiDealPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComiDealPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComiDealPaymentStrategy, [\n { gateway: 'checkoutcom', id: 'ideal' },\n]);\n","import {\n CreditCardInstrument,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInstrument,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithDocumentInstrument } from '../checkoutcom';\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst DOCUMENT_SUPPORTED_APMS = ['boleto', 'oxxo', 'qpay', 'ideal'];\n\nexport default class CheckoutComAPMPaymentStrategy extends CheckoutComCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData as PaymentInstrument,\n ),\n },\n });\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument | (CreditCardInstrument & WithDocumentInstrument),\n ): WithDocumentInstrument {\n const formattedPayload: WithDocumentInstrument = { ccDocument: '' };\n const ccDocument = 'ccDocument' in paymentData ? paymentData.ccDocument : '';\n\n if (DOCUMENT_SUPPORTED_APMS.indexOf(methodId) !== -1 && ccDocument) {\n formattedPayload.ccDocument = ccDocument;\n }\n\n return formattedPayload;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CheckoutComCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nimport CheckoutComAPMPaymentStrategy from './checkoutcom-apm-payment-strategy';\n\nconst createCheckoutComAPMPaymentStrategy: PaymentStrategyFactory<\n CheckoutComCustomPaymentStrategy\n> = (paymentIntegrationService) => {\n return new CheckoutComAPMPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCheckoutComAPMPaymentStrategy, [\n { gateway: 'checkoutcom' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotCompletedError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpayScriptLoader from './clearpay-script-loader';\nimport ClearpaySdk from './clearpay-sdk';\n\nexport default class ClearpayPaymentStrategy implements PaymentStrategy {\n private _clearpaySdk?: ClearpaySdk;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _clearpayScriptLoader: ClearpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId, options.gatewayId);\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod);\n }\n\n deinitialize(): Promise {\n this._clearpaySdk = undefined;\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { gatewayId, methodId } = payload.payment || {};\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const state = this._paymentIntegrationService.getState();\n const { isStoreCreditApplied: useStoreCredit } = state.getCheckoutOrThrow();\n\n await this._paymentIntegrationService.applyStoreCredit(useStoreCredit);\n\n await this._paymentIntegrationService.validateCheckout(state.getCheckout(), options);\n\n const { countryCode } = state.getBillingAddressOrThrow();\n\n if (!this._isCountrySupported(countryCode)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because billing country is not supported.',\n );\n }\n\n await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToClearpay(\n countryCode,\n this._paymentIntegrationService.getState().getPaymentMethod(methodId, gatewayId),\n );\n\n // Clearpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(noop);\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const payment = state.getPaymentId();\n const config = state.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._paymentIntegrationService.submitOrder({}, options);\n\n try {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._paymentIntegrationService.forgetCheckout(payment.providerId);\n await this._paymentIntegrationService.loadPaymentMethods();\n\n if (isRequestError(error)) {\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n }\n\n private async _redirectToClearpay(\n countryCode: string,\n paymentMethod?: PaymentMethod,\n ): Promise {\n if (!this._clearpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._clearpaySdk.initialize({ countryCode });\n this._clearpaySdk.redirect({ token: paymentMethod.clientToken });\n\n return Promise.resolve();\n }\n\n private _isCountrySupported(countryCode: string): boolean {\n return countryCode === 'GB';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n });\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Clearpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpaySdk from './clearpay-sdk';\nimport ClearpayWindow from './clearpay-window';\n\nconst SCRIPTS_DEFAULT = {\n PROD: '//portal.clearpay.co.uk/afterpay-async.js',\n SANDBOX: '//portal.sandbox.clearpay.co.uk/afterpay-async.js',\n};\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean): string {\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ClearpayPaymentStrategy from './clearpay-payment-strategy';\nimport ClearpayScriptLoader from './clearpay-script-loader';\n\nconst createClearpayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new ClearpayPaymentStrategy(\n paymentIntegrationService,\n new ClearpayScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createClearpayPaymentStrategy, [\n { gateway: 'clearpay' },\n { id: 'clearpay' },\n]);\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CreditCardPaymentStrategy from './credit-card-payment-strategy';\n\nconst createCreditCardPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CreditCardPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCreditCardPaymentStrategy, [{ default: true }]);\n","import { merge, some } from 'lodash';\n\nimport {\n HostedForm,\n isRequestError,\n isVaultedInstrument,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlow {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n await this._cardinalClient.configure(await this._getClientToken(method));\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const { getCardInstrument, getPaymentMethodOrThrow } =\n this._paymentIntegrationService.getState();\n\n const { payment: { methodId = '', paymentData = {} } = {} } = payload;\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const bin = instrument ? instrument.iin : hostedForm && hostedForm.getBin();\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await execute(\n merge(payload, {\n payment: {\n paymentData: {\n threeDSecure: { token: getPaymentMethodOrThrow(methodId).clientToken },\n },\n },\n }),\n options,\n );\n } catch (error) {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n const threeDSecure = await this._cardinalClient.getThreeDSecureData(\n error.body.three_ds_result,\n this._getOrderData(),\n );\n\n if (!hostedForm) {\n await this._paymentIntegrationService.submitPayment(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n\n return;\n }\n\n await hostedForm.submit(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n }\n }\n\n private async _getClientToken(method: PaymentMethod): Promise {\n if (method.clientToken) {\n return method.clientToken;\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(method.id);\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(method.id);\n\n return paymentMethod.clientToken || '';\n }\n\n private _getOrderData(): CardinalOrderData {\n const state = this._paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const shippingAddress = state.getShippingAddress();\n const checkout = state.getCheckoutOrThrow();\n const order = state.getOrderOrThrow();\n\n return {\n billingAddress,\n shippingAddress,\n currencyCode: checkout.cart.currency.code,\n id: order.orderId.toString(),\n amount: checkout.cart.cartAmount,\n };\n }\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport type setupCompleteFn = (setupCompleteData: CardinalSetupCompletedData) => void;\nexport type validatedFn = (data: CardinalValidatedData, jwt?: string) => void;\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted]: setupCompleteFn;\n [CardinalEventType.Validated]: validatedFn;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes, noop } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n CreditCardInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentMethodFailedError,\n ThreeDSecureToken,\n ThreeDsResult,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(noop);\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(noop),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { CardinalThreeDSecureFlow } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CyberSourcePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(_paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CyberSourcePaymentStrategy from './cybersource-payment-strategy';\n\nconst createCyberSourcePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CyberSourcePaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlow(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n};\n\nexport default toResolvableModule(createCyberSourcePaymentStrategy, [{ id: 'cybersource' }]);\n","import { merge, some } from 'lodash';\n\nimport {\n HostedForm,\n isCreditCardInstrument,\n isRequestError,\n isVaultedInstrument,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const { getCardInstrument } = this._paymentIntegrationService.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (isRequestError(error) && error.body?.status === 'additional_action_required') {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (err) {\n if (\n isRequestError(err) &&\n some(err.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = err.body.three_ds_result;\n const threeDsToken = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return this._submitPayment(payment, { token: threeDsToken }, hostedForm);\n }\n\n throw err;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._paymentIntegrationService.getState();\n const billingAddress = store.getBillingAddressOrThrow();\n const shippingAddress = store.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.getCheckoutOrThrow();\n const id = store.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n await hostedForm?.submit(paymentPayload);\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: PaymentIntegrationSelectors['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardInstrument(paymentData) && paymentData.ccNumber;\n const hostedFormBin = hostedForm ? hostedForm.getBin() : ccNumber;\n const bin = instrument ? instrument.iin : hostedFormBin;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument } from './payment';\n\nexport default function isCreditCardInstrument(\n instrument: unknown,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { CardinalThreeDSecureFlowV2 } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class CyberSourceV2PaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(_paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const { getPaymentMethodOrThrow } = this._paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlowV2,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CyberSourceV2PaymentStrategy from './cybersourcev2-payment-strategy';\n\nconst createCyberSourceV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CyberSourceV2PaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlowV2(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n};\n\nexport default toResolvableModule(createCyberSourceV2PaymentStrategy, [{ id: 'cybersourcev2' }]);\n","export interface DigitalRiverWindow extends Window {\n /**\n * Object to create an instance of the DigitalRiver object. This is called a Digital River publishable API key\n * This function accepts an optional options object using the following format DigitalRiver(publishableApiKey{, options})\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n DigitalRiver?: DigitalRiverClass;\n}\n\nexport type DigitalRiverClass = new (\n apiKey: string,\n options?: DigitalRiverJSOptions,\n) => DigitalRiverJS;\n\nexport default interface DigitalRiverJS {\n createDropin(configuration: DigitalRiverDropInConfiguration): DigitalRiverDropIn;\n authenticateSource(\n data: DigitalRiverAuthenticateSourceRequest,\n ): Promise;\n createElement(type: string, options: DigitalRiverElementOptions): DigitalRiverElement;\n}\n\nexport interface DigitalRiverElementOptions {\n classes: {\n base: string;\n };\n compliance: {\n entity: string;\n };\n}\n\ninterface DigitalRiverAuthenticateSourceRequest {\n sessionId: string;\n sourceId: string;\n sourceClientSecret: string;\n}\n\nexport interface DigitalRiverAdditionalProviderData {\n source_id: string;\n source_client_secret: string;\n}\n\nexport interface DigitalRiverAuthenticateSourceResponse {\n status: AuthenticationSourceStatus;\n}\n\nexport enum AuthenticationSourceStatus {\n complete = 'complete',\n authentication_not_required = 'authentication_not_required',\n failed = 'failed',\n}\n\nexport interface DigitalRiverJSOptions {\n /**\n * The locale used to localize the various display and error strings within DigitalRiver.js\n * Currently supported locales:\n * ar-EG, cs-CZ, da-DK, de-AT, de-CH, de-DE, el-GR, en-AU, en-BE, en-CA, en-CH, en-DK, en-FI, en-GB, en-IE, en-IN,\n * en-MY, en-NL, en-NO, en-NZ, en-PR, en-SE, en-SG, en-US, en-ZA, es-AR, es-CL, es-CO, es-EC, es-ES, es-MX, es-PE,\n * es-VE, et-EE, fi-FI, fr-BE, fr-CA, fr-CH, fr-FR, hu-HU, it-CH, it-IT, iw-IL, ja-JP, ko-KR, lt-LT, lv-LV, nl-BE,\n * nl-NL, no-NO, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-YU, sv-SE, th-TH, tr-TR, zh-CN, zh-HK, zh-TW\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n locale?: string;\n}\n\n/**\n * Create a Configuration object for Drop-in\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-5-configure-hydrate\n */\nexport interface DigitalRiverDropInConfiguration {\n /**\n * The payment session identifier returned by Digital River.\n */\n sessionId: string;\n\n /**\n * you can specify options to trigger different features or functionality\n */\n options?: OptionsResponse;\n billingAddress: {\n firstName: string;\n lastName: string;\n email: string;\n phoneNumber: string;\n address: {\n line1: string;\n line2?: string;\n city?: string;\n state?: string;\n postalCode: string;\n country: string;\n };\n };\n\n /**\n * Additional configuration details for configuration structure (classes, styles etc..)\n */\n paymentMethodConfiguration?: BaseElementOptions;\n\n /**\n * The function called when the shopper has authorized payment and a payment source has been successfully created.\n */\n onSuccess?(data: OnSuccessResponse): void;\n\n /**\n * The function called when the shopper cancels the payment process before authorizing payment.\n */\n onCancel?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when an error has occurred.\n */\n onError?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when Drop-in is ready for user interaction.\n */\n onReady?(data: OnReadyResponse): void;\n}\n\nexport interface OnCancelOrErrorResponse {\n /**\n * If an error occurs, Drop-in emits an event that identifies the payment method associated with the error.\n * Instruct your customer to provide a new method of payment.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onerror\n * Or When your customer chooses to pay with a specific payment method and decides to cancel during the redirect phase,\n * Drop-in emits an event that identifies the cancelled payment method.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#oncancel\n */\n errors: ErrorData[];\n}\n\nexport interface ErrorData {\n code: string;\n message: string;\n}\n\nexport interface OnReadyResponse {\n /**\n * When ready, Drop-in will emit an event that contains a \"paymentMethodTypes\" array of the available payment methods.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onready\n */\n paymentMethodTypes: string[];\n}\n\n/**\n * When creating your Drop-in instance, you can specify options to trigger different features or functionality.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options\n */\nexport interface OptionsResponse {\n /**\n * Use this option if you are using Drop-in within a standard checkout flow. Example Value: \"checkout\"\n */\n flow?: string;\n\n /**\n * When enabled, presents the customer with an option to save their payment details for future use within Drop-in.\n * Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate\n * any necessary Strong Customer Authentication.\n * If disabled, Drop-in will not present the customer with an option to save their payment details.\n */\n showSavePaymentAgreement?: boolean;\n\n /**\n * Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.\n */\n showComplianceSection?: boolean;\n\n /**\n * Use this option to customize the text of the Drop-in button.\n */\n button?: ButtonResponse;\n\n /**\n * Use this option to specify the future use of a source.\n */\n usage?: string;\n\n /**\n * Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.\n */\n showTermsOfSaleDisclosure?: boolean;\n\n /**\n * Additional configuration details for drop-in.\n */\n paymentMethodConfiguration?: BaseElementOptions;\n}\n\nexport interface ButtonResponse {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#customizing-the-text-of-the-drop-in-button\n * The text of the Drop-in button is customizable. You can either display pre-configured text or you can specify a unique text\n * Examples type: \"payNow\" || type: \"buyNow\" || type: \"completeOrder\" || type: \"submitOrder\"\n */\n type: string;\n}\n\nexport interface OnSuccessResponse {\n /**\n * Event that gets triggered after the customer's payment has provided with the necessary details for payment\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onsuccess\n */\n source: {\n id: string;\n reusable: boolean;\n browserInfo?: {\n browserIp?: string;\n };\n owner?: {\n email: string;\n firstName: string;\n lastName: string;\n phoneNumber: string;\n address: {\n city: string;\n country: string;\n line1: string;\n postalCode: string;\n state: string;\n };\n };\n };\n\n /**\n * Indicates whether the source has been enabled for future use.\n * Important: If this value is true, it does not mean the customer can use this source multiple times.\n * This flag identifies whether the necessary downstream actions have been triggered to prepare the source for storage.\n * You must attach the source to your customer for it to be truly reusable.\n */\n readyForStorage: boolean;\n}\n\nexport interface DigitalRiverDropIn {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface DigitalRiverElement {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface BaseElementOptions {\n /**\n * Set custom class names on the container DOM element when the Digital River element is in a particular state.\n */\n classes?: DigitalRiverElementClasses;\n /**\n * Use disabledPaymentMethods to disable specific payment methods.\n */\n disabledPaymentMethods?: string[];\n}\n\n/**\n * Custom classes\n * You can specify custom classes as part of a Class object included within the Options object when you create or\n * update an element. If you do not provide custom classes, the system uses the default options.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/elements#custom-classes\n */\nexport interface DigitalRiverElementClasses {\n /**\n * The Element is in its base state. The user either has not entered anything into the input field or is currently typing.\n */\n base?: string;\n\n /**\n * The Element is in its complete state. The user has input value, and it meets the basic validation requirements of that field.\n */\n complete?: string;\n\n /**\n * The Element is empty. The Element once had value but is now empty.\n */\n empty?: string;\n\n /**\n * The Element has focus.\n */\n focus?: string;\n\n /**\n * The Element has value, but it does not meet the basic validation requirements of the field.\n */\n invalid?: string;\n\n /**\n * The element has a value that has been automatically filled by the browser.\n */\n webkitAutofill?: string;\n}\n\nexport interface DigitalRiverInitializeToken {\n sessionId: string;\n checkoutData: DigitalRiverCheckoutData;\n}\n\ninterface DigitalRiverCheckoutData {\n checkoutId: string;\n sellingEntity: string;\n}\n\nexport interface DigitalRiverInitializationData {\n publicKey: string;\n paymentLanguage: string;\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nconst defaultMessage =\n 'There was an error while processing your payment. Please try again or contact us.';\n\nexport default class DigitalRiverError extends StandardError {\n constructor(type: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.type = type;\n this.name = name;\n }\n}\n","import { some } from 'lodash';\n\nimport {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverJS, {\n AuthenticationSourceStatus,\n DigitalRiverAdditionalProviderData,\n DigitalRiverAuthenticateSourceResponse,\n DigitalRiverDropIn,\n DigitalRiverElementOptions,\n DigitalRiverInitializationData,\n DigitalRiverInitializeToken,\n OnCancelOrErrorResponse,\n OnReadyResponse,\n OnSuccessResponse,\n} from './digitalriver';\nimport DigitalRiverError from './digitalriver-error';\nimport DigitalRiverPaymentInitializeOptions, {\n WithDigitalRiverPaymentInitializeOptions,\n} from './digitalriver-payment-initialize-options';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nexport default class DigitalRiverPaymentStrategy implements PaymentStrategy {\n private digitalRiverJS?: DigitalRiverJS;\n private digitalRiverDropComponent?: DigitalRiverDropIn;\n private submitFormEvent?: () => void;\n private loadSuccessResponse?: OnSuccessResponse;\n private digitalRiverCheckoutData?: DigitalRiverInitializeToken;\n private unsubscribe?: () => void;\n private digitalRiverInitializeOptions?: DigitalRiverPaymentInitializeOptions;\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private digitalRiverScriptLoader: DigitalRiverScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithDigitalRiverPaymentInitializeOptions,\n ): Promise {\n this.digitalRiverInitializeOptions = options.digitalriver;\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { publicKey, paymentLanguage: locale } = paymentMethod.initializationData || {};\n const { containerId } = this.getDigitalRiverInitializeOptions();\n\n if (!publicKey || !locale) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publicKey\" or \"locale\" argument is not provided.',\n );\n }\n\n this.digitalRiverJS = await this.digitalRiverScriptLoader.load(publicKey, locale);\n\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n async (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n\n this.digitalRiverJS = await this.digitalRiverScriptLoader.load(\n publicKey,\n locale,\n );\n }\n\n await this.loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n this.loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n const { containerId } = this.getDigitalRiverInitializeOptions();\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n }\n\n return Promise.resolve();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, methodId } = payment;\n const { shouldSetAsDefaultInstrument = false } = isHostedInstrumentLike(paymentData)\n ? paymentData\n : {};\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (!this.digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (isVaultedInstrument(paymentData)) {\n try {\n await this.submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this.digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n false,\n );\n } catch (error) {\n if (!this.isAuthenticateSourceAction(error)) {\n throw error;\n }\n\n const confirm =\n isRequestError(error) &&\n (await this.authenticateSource(error.body.provider_data));\n\n await this.submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this.digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n confirm,\n );\n }\n } else {\n if (!this.loadSuccessResponse) {\n throw new PaymentArgumentInvalidError(['this.loadSuccessResponse']);\n }\n\n const paymentPayload = {\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n checkoutId: this.digitalRiverCheckoutData.checkoutData.checkoutId,\n source: this.loadSuccessResponse,\n sessionId: this.digitalRiverCheckoutData.sessionId,\n }),\n },\n vault_payment_instrument: this.loadSuccessResponse.readyForStorage,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private getDigitalRiverJs(): DigitalRiverJS {\n if (!this.digitalRiverJS) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.digitalRiverJS;\n }\n\n private getErrorMessage(error: OnCancelOrErrorResponse): string {\n const { errors } = error;\n\n return errors.map((e) => `code: ${e.code} message: ${e.message}`).join('\\n');\n }\n\n private async onSuccessResponse(data?: OnSuccessResponse): Promise {\n const error = new InvalidArgumentError(\n 'Unable to initialize payment because success argument is not provided.',\n );\n\n if (data && this.submitFormEvent) {\n const { browserInfo, owner } = data.source;\n\n this.loadSuccessResponse = browserInfo\n ? {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n ...browserInfo,\n },\n readyForStorage: data.readyForStorage,\n }\n : {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n },\n readyForStorage: data.readyForStorage,\n };\n\n if (owner) {\n const billingAddressPayPal = {\n firstName: owner.firstName,\n lastName: owner.lastName,\n city: owner.address.city,\n company: '',\n address1: owner.address.line1,\n address2: '',\n postalCode: owner.address.postalCode,\n countryCode: owner.address.country,\n phone: owner.phoneNumber,\n stateOrProvince: owner.address.state,\n stateOrProvinceCode: owner.address.country,\n customFields: [],\n email: owner.email || owner.email,\n };\n\n this.loadSuccessResponse.source.owner = data.source.owner;\n await this.paymentIntegrationService.updateBillingAddress(billingAddressPayPal);\n }\n\n return this.submitFormEvent();\n }\n\n return this.getDigitalRiverInitializeOptions().onError?.(error);\n }\n\n private onReadyResponse(data?: OnReadyResponse): void {\n if (data) {\n this.getDigitalRiverInitializeOptions().onRenderButton?.();\n }\n }\n\n private getDigitalRiverInitializeOptions(): DigitalRiverPaymentInitializeOptions {\n if (!this.digitalRiverInitializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.digitalRiverInitializeOptions;\n }\n\n private async loadWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n try {\n const state = await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n const billing = state.getBillingAddressOrThrow();\n const customer = state.getCustomerOrThrow();\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n const { paymentMethodConfiguration } =\n this.getDigitalRiverInitializeOptions().configuration;\n const { containerId, configuration } = this.getDigitalRiverInitializeOptions();\n const { clientToken } = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.digitalRiverCheckoutData = JSON.parse(clientToken);\n\n if (!this.digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.mountComplianceSection(this.digitalRiverCheckoutData.checkoutData.sellingEntity);\n\n this.submitFormEvent = this.getDigitalRiverInitializeOptions().onSubmitForm;\n\n const disabledPaymentMethods = features['PROJECT-4802.digital_river_paypal_support']\n ? []\n : ['payPal'];\n\n const digitalRiverConfiguration = {\n sessionId: this.digitalRiverCheckoutData.sessionId,\n options: {\n ...configuration,\n showSavePaymentAgreement:\n Boolean(customer.email) && configuration.showSavePaymentAgreement,\n },\n billingAddress: {\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email || customer.email,\n phoneNumber: billing.phone,\n address: {\n line1: billing.address1,\n line2: billing.address2,\n city: billing.city,\n state: billing.stateOrProvinceCode,\n postalCode: billing.postalCode,\n country: billing.countryCode,\n },\n },\n paymentMethodConfiguration: {\n ...paymentMethodConfiguration,\n disabledPaymentMethods,\n },\n onSuccess: (data?: OnSuccessResponse) => {\n this.onSuccessResponse(data);\n },\n onReady: (data?: OnReadyResponse) => {\n this.onReadyResponse(data);\n },\n onError: (error: OnCancelOrErrorResponse) => {\n const descriptiveError = new Error(this.getErrorMessage(error));\n\n this.getDigitalRiverInitializeOptions().onError?.(descriptiveError);\n },\n };\n\n this.digitalRiverDropComponent =\n this.getDigitalRiverJs().createDropin(digitalRiverConfiguration);\n this.digitalRiverDropComponent.mount(containerId);\n\n return state;\n } catch {\n throw new DigitalRiverError(\n 'payment.digitalriver_checkout_error',\n 'digitalRiverCheckoutError',\n );\n }\n }\n\n private isAuthenticateSourceAction(error: unknown): boolean {\n return !(\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n );\n }\n\n private async authenticateSource(\n additionalAction: DigitalRiverAdditionalProviderData,\n ): Promise {\n if (!this.digitalRiverCheckoutData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because payload payment argument is not provided.',\n );\n }\n\n const authenticateSourceResponse: DigitalRiverAuthenticateSourceResponse =\n await this.getDigitalRiverJs().authenticateSource({\n sessionId: this.digitalRiverCheckoutData.sessionId,\n sourceId: additionalAction.source_id,\n sourceClientSecret: additionalAction.source_client_secret,\n });\n\n if (authenticateSourceResponse.status === AuthenticationSourceStatus.failed) {\n throw new Error('Source authentication failed, please try again');\n }\n\n return (\n authenticateSourceResponse.status === AuthenticationSourceStatus.complete ||\n authenticateSourceResponse.status ===\n AuthenticationSourceStatus.authentication_not_required\n );\n }\n\n private async submitVaultedInstrument(\n methodId: string,\n instrumentId: string,\n checkoutId: string,\n shouldSetAsDefaultInstrument: boolean,\n confirm: boolean,\n ): Promise {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n token: instrumentId,\n },\n credit_card_token: {\n token: JSON.stringify({\n checkoutId,\n }),\n },\n confirm,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n };\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private mountComplianceSection(sellingEntity: string) {\n const complianceDiv = document.getElementById('compliance');\n\n const complianceOptions: DigitalRiverElementOptions = {\n classes: {\n base: 'DRElement',\n },\n compliance: {\n entity: sellingEntity,\n },\n };\n\n if (complianceDiv) {\n complianceDiv.innerHTML = '';\n\n const complianceElement = this.getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n } else {\n const drfooter = document.createElement('div');\n\n drfooter.setAttribute('id', 'compliance');\n drfooter.style.cssText = 'min-height: 45px;';\n drfooter.classList.add('layout');\n document.body.appendChild(drfooter);\n\n const complianceElement = this.getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n }\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverJS, { DigitalRiverWindow } from './digitalriver';\n\nexport default class DigitalRiverScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stylesheetLoader: StylesheetLoader,\n private _window: DigitalRiverWindow = window,\n ) {}\n\n async load(publicKey: string, locale: string): Promise {\n await Promise.all([\n this.stylesheetLoader.loadStylesheet(\n `https://js.digitalriverws.com/v1/css/DigitalRiver.css`,\n ),\n this.scriptLoader.loadScript(`https://js.digitalriverws.com/v1/DigitalRiver.js`),\n ]);\n\n if (!this._window.DigitalRiver) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(new this._window.DigitalRiver(publicKey, { locale }));\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport DigitalRiverPaymentStrategy from './digitalriver-payment-strategy';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nconst createDigitalRiverPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new DigitalRiverPaymentStrategy(\n paymentIntegrationService,\n new DigitalRiverScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n\nexport default toResolvableModule(createDigitalRiverPaymentStrategy, [{ id: 'digitalriver' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n isRequestError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, isAdditionalActionRequired } from './is-additional-action';\n\nexport default class ExternalPaymentStrategy implements PaymentStrategy {\n constructor(\n private _formPoster: FormPoster,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (\n !isRequestError(error) ||\n !isAdditionalActionRequired(error.body) ||\n !this._isAdditionalActionRequired(error.body)\n ) {\n return Promise.reject(error);\n }\n\n const {\n body: {\n additional_action_required: {\n data: { redirect_url },\n },\n },\n } = error;\n\n return new Promise(() => this.redirectUrl(redirect_url));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n protected redirectUrl(redirect_url: string): void {\n return this._formPoster.postForm(redirect_url, {});\n }\n\n private _isAdditionalActionRequired(body: AdditionalActionRequired): boolean {\n const { additional_action_required, status } = body;\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'offsite_redirect'\n );\n }\n}\n","export interface AdditionalActionRequired {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n type: string;\n };\n status: string;\n}\n\nexport function isAdditionalActionRequired(value: unknown): value is AdditionalActionRequired {\n return typeof value === 'object' && value !== null && 'additional_action_required' in value;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ExternalPaymentStrategy from './external-payment-strategy';\n\nconst createExternalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new ExternalPaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createExternalPaymentStrategy, [{ id: 'laybuy' }]);\n","import { AdyenAdditionalActionErrorResponse } from '../types';\n\nexport default function isAdditionalActionRequiredErrorResponse(\n param: unknown,\n): param is AdyenAdditionalActionErrorResponse {\n return (\n typeof param === 'object' &&\n param !== null &&\n 'errors' in (param as AdyenAdditionalActionErrorResponse) &&\n Array.isArray((param as AdyenAdditionalActionErrorResponse).errors) &&\n 'code' in (param as AdyenAdditionalActionErrorResponse).errors[0] &&\n typeof (param as AdyenAdditionalActionErrorResponse).errors[0].code === 'string' &&\n 'provider_data' in param &&\n typeof (param as AdyenAdditionalActionErrorResponse).provider_data === 'object'\n );\n}\n","import {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV2ScriptLoader,\n isAdditionalActionRequiredErrorResponse,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAdyenV2 extends GooglePayGateway {\n private _adyenClient?: AdyenClient;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _scriptLoader: AdyenV2ScriptLoader) {\n super('adyen', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n const state = this._service.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n });\n\n return Promise.resolve();\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n const paymentMethod = super.getPaymentMethod();\n\n return JSON.stringify({\n type: paymentMethod.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isRequestError(error) || !isAdditionalActionRequiredErrorResponse(error.body)) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._service.submitPayment(payment);\n } catch (e) {\n return this.processAdditionalAction(e);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { round } from 'lodash';\n\nimport {\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayPaymentInitializeOptions, {\n WithGooglePayPaymentInitializeOptions,\n} from './google-pay-payment-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n CallbackTriggerType,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _paymentButton?: HTMLElement;\n private _clickListener?: (event: MouseEvent) => unknown;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n\n constructor(\n protected _paymentIntegrationService: PaymentIntegrationService,\n protected _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithGooglePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n const googlePayOptions = options[this._getMethodId()];\n\n if (!googlePayOptions?.walletButton) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n const { walletButton, ...callbacks } = googlePayOptions;\n\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(this._getMethodId());\n\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(paymentMethod.initializationData?.storeCountry),\n );\n\n this._addPaymentButton(walletButton, callbacks);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n await this._paymentIntegrationService.submitOrder();\n\n const nonce = await this._googlePayPaymentProcessor.getNonce(payment.methodId);\n const extraData = await this._googlePayPaymentProcessor.extraPaymentData();\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce, ...extraData },\n });\n } catch (error) {\n await this._googlePayPaymentProcessor.processAdditionalAction(error, payment.methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._clickListener) {\n this._paymentButton?.removeEventListener('click', this._clickListener);\n }\n\n this._paymentButton = undefined;\n this._clickListener = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n protected _addPaymentButton(\n walletButton: string,\n callbacks: Omit,\n ): void {\n if (this._paymentButton) {\n return;\n }\n\n const paymentButton = document.getElementById(walletButton);\n\n if (!paymentButton) {\n throw new InvalidArgumentError('Unable to proceed without a walletButton.');\n }\n\n this._paymentButton = paymentButton;\n this._clickListener = this._handleClick(callbacks);\n\n this._paymentButton.addEventListener('click', this._clickListener);\n }\n\n protected _handleClick({\n onPaymentSelect,\n onError,\n }: Omit): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n // TODO: Dispatch Widget Actions\n try {\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n\n onPaymentSelect?.();\n };\n }\n\n protected async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutXhr(this._getMethodId(), response);\n\n await this._paymentIntegrationService.loadCheckout();\n await this._paymentIntegrationService.loadPaymentMethod(this._getMethodId());\n }\n\n protected _getMethodId(): keyof WithGooglePayPaymentInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n protected _getGooglePayClientOptions(countryCode?: string): GooglePayPaymentOptions {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n }: IntermediatePaymentData): Promise => {\n if (callbackTrigger !== CallbackTriggerType.INITIALIZE) {\n return;\n }\n\n await this._paymentIntegrationService.loadCheckout();\n\n const { getCheckoutOrThrow, getCartOrThrow } =\n this._paymentIntegrationService.getState();\n const { code: currencyCode, decimalPlaces } = getCartOrThrow().currency;\n const totalPrice = round(\n getCheckoutOrThrow().outstandingBalance,\n decimalPlaces,\n ).toFixed(decimalPlaces);\n\n return {\n newTransactionInfo: {\n ...(countryCode && { countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n };\n },\n },\n };\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV2ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAdyenV2Gateway from '../../gateways/google-pay-adyenv2-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAdyenV2Gateway(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAdyenV2PaymentStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV3ScriptLoader,\n isAdditionalActionRequiredErrorResponse,\n} from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { GooglePayInitializationData } from '../types';\n\nimport GooglePayGateway from './google-pay-gateway';\n\nexport default class GooglePayAdyenV3 extends GooglePayGateway {\n private _adyenClient?: AdyenClient;\n private _service: PaymentIntegrationService;\n\n constructor(service: PaymentIntegrationService, private _scriptLoader: AdyenV3ScriptLoader) {\n super('adyen', service);\n\n this._service = service;\n }\n\n async initialize(\n getPaymentMethod: () => PaymentMethod,\n isBuyNowFlow?: boolean,\n currencyCode?: string,\n ): Promise {\n await super.initialize(getPaymentMethod, isBuyNowFlow, currencyCode);\n\n const paymentMethod = super.getPaymentMethod();\n const state = this._service.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n });\n\n return Promise.resolve();\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (!isRequestError(error) || !isAdditionalActionRequiredErrorResponse(error.body)) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._service.submitPayment(payment);\n } catch (e) {\n return this.processAdditionalAction(e);\n }\n }\n\n async getNonce(methodId: string) {\n const nonce = await super.getNonce(methodId);\n const paymentMethod = super.getPaymentMethod();\n\n return JSON.stringify({\n type: paymentMethod.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { AdyenV3ScriptLoader } from '@bigcommerce/checkout-sdk/adyen-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAdyenV3Gateway from '../../gateways/google-pay-adyenv3-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAdyenV3Gateway(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAdyenV3PaymentStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeNetPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAuthorizeNetPaymentStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComPaymentStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourcePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayCybersourcePaymentStrategy, [\n { id: 'googlepaycybersourcev2' },\n { id: 'googlepaybnz' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayOrbitalPaymentStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripePaymentStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayWorldpayAccessPaymentStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreePaymentStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","export type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\nexport interface PayPalSDK {\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (confirmOrderConfig: ConfirmOrderConfig) => Promise<{ status: string }>;\n initiatePayerAction: (payerActionConfig: PayerActionConfig) => Promise;\n };\n}\n\ninterface ConfirmOrderConfig {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n}\n\ninterface PayerActionConfig {\n orderId: string;\n}\n\nexport enum ConfirmOrderStatus {\n Approved = 'APPROVED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n}\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n}\n\nexport interface PayPalCommerceScriptParams {\n options: {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n };\n attributes: {\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n };\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n | 'buttons'\n | 'funding-eligibility'\n | 'hosted-fields'\n | 'messages'\n | 'payment-fields'\n | 'legal'\n | 'googlepay'\n | 'card-fields'\n>;\n\nexport interface GooglePayConfig {\n allowedPaymentMethods: AllowedPaymentMethods[];\n apiVersion: number;\n apiVersionMinor: number;\n countryCode: string;\n isEligible: boolean;\n merchantInfo: {\n merchantId: string;\n merchantOrigin: string;\n };\n}\n\nexport interface AllowedPaymentMethods {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n billingAddressRequired: boolean;\n assuranceDetailsRequired: boolean;\n billingAddressParameters: {\n format: string;\n };\n };\n tokenizationSpecification: {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId: string;\n };\n };\n}\n\nexport interface PayPalGoogleSdk {\n version: string;\n getCorrelationID: () => void;\n Googlepay: () => {\n config: () => Promise;\n confirmOrder: (arg0: {\n orderId: string;\n paymentMethodData: ConfirmOrderData;\n }) => Promise<{ status: string }>;\n initiatePayerAction: () => void;\n };\n FUNDING: Record;\n}\n\nexport interface ConfirmOrderData {\n tokenizationData: {\n type: string;\n token: string;\n };\n info: {\n cardNetwork: string;\n cardDetails: string;\n };\n type: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\nimport { GooglePayInitializationData, GooglePayPayPalCommerceInitializationData } from '../types';\n\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\nimport { ConfirmOrderData, ConfirmOrderStatus } from './types';\n\nexport default class GooglePayPaypalCommercePaymentStrategy extends GooglePayPaymentStrategy {\n constructor(\n _paymentIntegrationService: PaymentIntegrationService,\n _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n private _requestSender: RequestSender,\n ) {\n super(_paymentIntegrationService, _googlePayPaymentProcessor);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const state = this._paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const { initializationData } = state.getPaymentMethodOrThrow(\n this._getMethodId(),\n );\n const { orderId } = await this.getOrderId(cartId);\n\n const { card_information } = initializationData || {};\n const nonce = await this._googlePayPaymentProcessor.getNonce(payment.methodId);\n\n const confirmOrderData = {\n tokenizationData: {\n type: 'PAYMENT_GATEWAY',\n token: atob(nonce),\n },\n info: {\n cardNetwork: card_information?.type || '',\n cardDetails: card_information?.number || '',\n },\n type: 'CARD',\n };\n\n await this.confirmOrder(orderId, confirmOrderData);\n await this._paymentIntegrationService.submitOrder();\n\n try {\n const paymentData = {\n formattedPayload: {\n method_id: payment.methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n } catch (error) {\n await this._googlePayPaymentProcessor.processAdditionalAction(error);\n }\n }\n\n private async confirmOrder(orderId: string, confirmOrderData: ConfirmOrderData) {\n const state = this._paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(\n this._getMethodId(),\n );\n\n const currencyCode = state.getCartOrThrow().currency.code;\n\n const payPalSDK = await this._paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n true,\n );\n\n const { status } = await payPalSDK\n .Googlepay()\n .confirmOrder({ orderId, paymentMethodData: confirmOrderData });\n\n if (status === ConfirmOrderStatus.PayerActionRequired) {\n await payPalSDK.Googlepay().initiatePayerAction({ orderId });\n\n return Promise.resolve();\n }\n\n if (status !== ConfirmOrderStatus.Approved) {\n throw new InvalidArgumentError('Payment is not approved.');\n }\n\n return Promise.resolve();\n }\n\n private async getOrderId(cartId: string): Promise<{ orderId: string }> {\n const url = '/api/storefront/payments/googlepaypaypalcommercecheckout';\n const requestData = {\n cartId,\n shouldSaveInstrument: false,\n };\n\n const { body } = await this._requestSender.post<{ orderId: string }>(url, {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n },\n body: requestData,\n });\n\n return body;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../google-pay-payment-strategy';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport GooglePayPaypalCommercePaymentStrategy from './google-pay-paypal-commerce-payment-strategy';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommercePaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) => {\n const scriptLoader = new PayPalCommerceScriptLoader(getScriptLoader());\n\n return new GooglePayPaypalCommercePaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(paymentIntegrationService, scriptLoader),\n createRequestSender(),\n createFormPoster(),\n ),\n scriptLoader,\n createRequestSender(),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommercePaymentStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport GooglePayPaymentStrategy from '../../google-pay-payment-strategy';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartPaymentStrategy: PaymentStrategyFactory<\n GooglePayPaymentStrategy\n> = (paymentIntegrationService) =>\n new GooglePayPaymentStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartPaymentStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import StandardError from './standard-error';\n\nconst defaultMessage =\n 'Payment cannot be processed for this order, please select another payment method';\n\nexport default class PaymentExecuteError extends StandardError {\n type = 'custom_provider_execute_error';\n subtype: string;\n\n constructor(subtype: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.name = name;\n this.subtype = subtype;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentExecuteError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { HummInitializationData, OffsiteRedirectResponse } from './humm';\n\nexport default class HummPaymentStrategy implements PaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(payment.methodId, options);\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payment.methodId);\n\n if (!paymentMethod.initializationData?.processable) {\n throw new PaymentExecuteError(\n 'payment.humm_not_processable_error',\n 'hummNotProcessableError',\n );\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n });\n } catch (error) {\n if (this.isOffsiteRedirectResponse(error)) {\n return this.handleOffsiteRedirectResponse(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private handleOffsiteRedirectResponse(response: OffsiteRedirectResponse): Promise {\n const url = response.body.additional_action_required.data.redirect_url;\n const data = response.body.provider_data;\n\n return new Promise((resolve) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.formPoster.postForm(url, JSON.parse(data), resolve);\n });\n }\n\n private isOffsiteRedirectResponse(response: unknown): response is OffsiteRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n partialBody.additional_action_required.type === 'offsite_redirect' &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HummPaymentStrategy from './humm-payment-strategy';\n\nconst createHummPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new HummPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createHummPaymentStrategy, [{ id: 'humm' }]);\n","export const supportedCountries = [\n 'AT',\n 'BE',\n 'CA',\n 'CH',\n 'CZ',\n 'DE',\n 'DK',\n 'ES',\n 'FI',\n 'FR',\n 'GB',\n 'GR',\n 'IE',\n 'IT',\n 'NL',\n 'NO',\n 'NZ',\n 'PL',\n 'PT',\n 'SE',\n];\nexport const supportedCountriesRequiringStates = ['AU'];\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { includes } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from '../klarnav2/klarna-supported-countries';\n\nimport KlarnaCredit, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-credit';\nimport { WithKlarnaPaymentInitializeOptions } from './klarna-payment-initialize-options';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nexport default class KlarnaPaymentStrategy {\n private klarnaCredit?: KlarnaCredit;\n private unsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private klarnaScriptLoader: KlarnaScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithKlarnaPaymentInitializeOptions,\n ): Promise {\n this.klarnaCredit = await this.klarnaScriptLoader.load();\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n void this.loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n await this.loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n\n const { authorization_token: authorizationToken } = await this.authorize();\n\n await this.paymentIntegrationService.initializePayment(paymentPayload.methodId, {\n authorizationToken,\n });\n\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async loadWidget(\n options: PaymentInitializeOptions & WithKlarnaPaymentInitializeOptions,\n ): Promise {\n if (!options.klarna) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarna\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n klarna: { container, onLoad },\n } = options;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n return new Promise((resolve) => {\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!this.klarnaCredit || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.klarnaCredit.init({ client_token: paymentMethod.clientToken });\n\n this.klarnaCredit.load({ container }, (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n });\n });\n }\n\n private getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this.mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this.needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private authorize(): Promise {\n return new Promise((resolve, reject) => {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddress();\n const shippingAddress = state.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n if (!this.klarnaCredit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const updateSessionData = this.getUpdateSessionData(billingAddress, shippingAddress);\n\n this.klarnaCredit.authorize(updateSessionData, (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaCredit from './klarna-credit';\nimport KlarnaWindow from './klarna-window';\n\nconst SDK_URL = '//credit.klarnacdn.net/lib/v1/api.js';\n\nexport default class KlarnaScriptLoader {\n constructor(private scriptLoader: ScriptLoader, private klarnaWindow: KlarnaWindow = window) {}\n\n async load(): Promise {\n if (!this.klarnaWindow.Klarna?.Credit) {\n await this.scriptLoader.loadScript(SDK_URL);\n }\n\n if (!this.klarnaWindow.Klarna?.Credit) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.klarnaWindow.Klarna.Credit;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPaymentStrategy from './klarna-payment-strategy';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nconst createKlarnaPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new KlarnaPaymentStrategy(\n paymentIntegrationService,\n new KlarnaScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createKlarnaPaymentStrategy, [{ id: 'klarna' }]);\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { includes } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-payments';\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from './klarna-supported-countries';\nimport { WithKlarnaV2PaymentInitializeOptions } from './klarnav2-payment-initialize-options';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nexport default class KlarnaV2PaymentStrategy {\n private klarnaPayments?: KlarnaPayments;\n private unsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private klarnav2ScriptLoader: KlarnaV2ScriptLoader,\n private klarnav2TokenUpdater: KlarnaV2TokenUpdater,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithKlarnaV2PaymentInitializeOptions,\n ): Promise {\n this.klarnaPayments = await this.klarnav2ScriptLoader.load();\n\n this.unsubscribe = this.paymentIntegrationService.subscribe(\n (state) => {\n if (\n state.isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n void this.loadPaymentsWidget(options);\n }\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n await this.loadPaymentsWidget(options);\n }\n\n deinitialize(): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { ...paymentPayload },\n } = payload;\n const { gatewayId, methodId } = paymentPayload;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { id: cartId } = state.getCartOrThrow();\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n\n await this.klarnav2TokenUpdater.klarnaOrderInitialization(cartId, clientToken);\n\n const { authorization_token: authorizationToken } = await this.authorizeOrThrow(methodId);\n\n await this.paymentIntegrationService.initializePayment(gatewayId, {\n authorizationToken,\n });\n\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async loadPaymentsWidget(\n options: PaymentInitializeOptions & WithKlarnaV2PaymentInitializeOptions,\n ): Promise {\n if (!options.klarnav2) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarnav2\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n gatewayId,\n klarnav2: { container, onLoad },\n } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const params = { params: cartId };\n\n await this.klarnav2TokenUpdater.updateClientToken(gatewayId, { params }).catch(() => {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n });\n\n return new Promise((resolve) => {\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!this.klarnaPayments || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this.klarnaPayments.init({ client_token: paymentMethod.clientToken });\n this.klarnaPayments.load(\n { container, payment_method_category: paymentMethod.id },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this.mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this.mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this.needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private async authorizeOrThrow(methodId: string): Promise {\n await this.paymentIntegrationService.loadCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const shippingAddress = state.getShippingAddress();\n\n const updateSessionData = this.getUpdateSessionData(billingAddress, shippingAddress);\n\n return new Promise((resolve, reject) => {\n if (!this.klarnaPayments) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this.klarnaPayments.authorize(\n { payment_method_category: methodId },\n updateSessionData,\n (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaPayments from './klarna-payments';\nimport KlarnaV2Window from './klarnav2-window';\n\nconst SDK_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js';\n\nexport default class KlarnaV2ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private klarnaWindow: KlarnaV2Window = window,\n ) {}\n\n async load(): Promise {\n if (!this.klarnaWindow.Klarna?.Payments) {\n await this.scriptLoader.loadScript(SDK_URL);\n }\n\n if (!this.klarnaWindow.Klarna?.Payments) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.klarnaWindow.Klarna.Payments;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n PaymentMethod,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class KlarnaV2TokenUpdater {\n constructor(private requestSender: RequestSender) {}\n\n updateClientToken(\n gatewayId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${gatewayId}`;\n\n return this.requestSender.get(url, {\n timeout,\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n async klarnaOrderInitialization(\n cartId: string,\n clientToken: string | undefined,\n ): Promise {\n const url = `/api/storefront/initialization/klarna`;\n const options = {\n headers: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n cartId,\n clientToken,\n },\n };\n\n await this.requestSender.put(url, options);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport KlarnaV2PaymentStrategy from './klarnav2-payment-strategy';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nconst createKlarnaV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const requestSender = createRequestSender({ host: getHost() });\n\n return new KlarnaV2PaymentStrategy(\n paymentIntegrationService,\n new KlarnaV2ScriptLoader(getScriptLoader()),\n new KlarnaV2TokenUpdater(requestSender),\n );\n};\n\nexport default toResolvableModule(createKlarnaV2PaymentStrategy, [{ gateway: 'klarna' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class LegacyPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(payload, options);\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport LegacyPaymentStrategy from './legacy-payment-strategy';\n\nconst createLegacyPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new LegacyPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createLegacyPaymentStrategy, [{ id: 'testgateway' }]);\n","import { each, some } from 'lodash';\n\nimport {\n getBrowserInfo,\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { MollieClient, MollieElement } from './mollie';\nimport MolliePaymentInitializeOptions, {\n WithMolliePaymentInitializeOptions,\n} from './mollie-payment-initialize-options';\nimport MollieScriptLoader from './mollie-script-loader';\n\nexport enum MolliePaymentMethodType {\n CREDIT_CARD = 'credit_card',\n}\n\nconst methodsNotAllowedWhenDigitalOrder = ['klarnapaylater', 'klarnasliceit'];\n\nexport default class MolliePaymentStrategy implements PaymentStrategy {\n private initializeOptions?: MolliePaymentInitializeOptions;\n private mollieClient?: MollieClient;\n private cardHolderElement?: MollieElement;\n private cardNumberElement?: MollieElement;\n private verificationCodeElement?: MollieElement;\n private expiryDateElement?: MollieElement;\n private locale?: string;\n\n private hostedForm?: HostedForm;\n\n private unsubscribe?: () => void;\n\n constructor(\n private mollieScriptLoader: MollieScriptLoader,\n private paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithMolliePaymentInitializeOptions,\n ): Promise {\n const { mollie, methodId, gatewayId } = options;\n\n if (!mollie) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.mollie\" argument is not provided.',\n );\n }\n\n if (!methodId || !gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" and/or \"gatewayId\" argument is not provided.',\n );\n }\n\n const controllers = document.querySelectorAll('.mollie-components-controller');\n\n each(controllers, (controller) => controller.remove());\n\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n\n this.initializeOptions = mollie;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n const {\n config: { merchantId, testMode },\n } = paymentMethod;\n\n this.locale = state.getLocale();\n\n if (!merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this.isCreditCard(methodId) &&\n mollie.form &&\n this.shouldShowTSVHostedForm(methodId, gatewayId)\n ) {\n this.hostedForm = await this.mountCardVerificationfields(mollie.form);\n } else if (this.isCreditCard(methodId)) {\n this.mollieClient = await this.loadMollieJs(\n merchantId,\n storeConfig.storeProfile.storeLanguage,\n testMode,\n );\n this.mountElements();\n }\n\n this.unsubscribe = () => {\n if (\n this.paymentIntegrationService.getState().isPaymentMethodInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const element = document.getElementById(`${gatewayId}-${methodId}-paragraph`);\n\n if (element) {\n element.remove();\n }\n\n mollie.disableButton(false);\n\n this.loadPaymentMethodsAllowed(mollie, methodId, gatewayId);\n }\n };\n\n this.unsubscribe();\n\n this.loadPaymentMethodsAllowed(mollie, methodId, gatewayId);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !payment.gatewayId || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment', 'gatewayId', 'paymentData']);\n }\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (isVaultedInstrument(paymentData)) {\n return await this.executeWithVaulted(payment);\n }\n\n if (this.isCreditCard(payment.methodId)) {\n return await this.executeWithCC(payment);\n }\n\n return await this.executeWithAPM(payment);\n } catch (error) {\n await this.processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(options?: PaymentRequestOptions): Promise {\n if (this.unsubscribe) {\n this.unsubscribe();\n }\n\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n if (options && options.methodId && options.gatewayId && !this.hostedForm) {\n const element = document.getElementById(`${options.gatewayId}-${options.methodId}`);\n\n if (element) {\n element.remove();\n }\n } else if (options && options.methodId && this.isCreditCard(options.methodId)) {\n if (\n this.cardHolderElement &&\n this.cardNumberElement &&\n this.verificationCodeElement &&\n this.expiryDateElement\n ) {\n this.cardHolderElement.unmount();\n this.cardHolderElement = undefined;\n\n this.cardNumberElement.unmount();\n this.cardNumberElement = undefined;\n\n this.verificationCodeElement.unmount();\n this.verificationCodeElement = undefined;\n\n this.expiryDateElement.unmount();\n this.expiryDateElement = undefined;\n }\n }\n\n this.mollieClient = undefined;\n\n return Promise.resolve();\n }\n\n protected async executeWithCC(payment: OrderPaymentRequestBody): Promise {\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { token, error } = await this.getMollieClient().createToken();\n\n /* eslint-disable */\n if (error) {\n return Promise.reject(error);\n }\n\n const formattedPayload = {\n credit_card_token: {\n token,\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n browser_info: getBrowserInfo(),\n shopper_locale: this.getShopperLocale(),\n };\n /* eslint-enable */\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload,\n },\n });\n }\n\n protected async executeWithVaulted(payment: OrderPaymentRequestBody): Promise {\n if (this.isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) {\n const form = this.hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n await this.paymentIntegrationService.loadCurrentOrder();\n } else {\n await this.paymentIntegrationService.submitPayment(payment);\n }\n }\n\n protected async executeWithAPM(payment: OrderPaymentRequestBody): Promise {\n const paymentData = payment.paymentData;\n const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : '';\n\n await this.paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: {\n issuer,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n shopper_locale: this.getShopperLocale(),\n },\n },\n });\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === MolliePaymentMethodType.CREDIT_CARD;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this.isHostedPaymentFormEnabled(methodId, gatewayId) && this.isHostedFieldAvailable()\n );\n }\n\n private mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n /* eslint-disable */\n return new Promise(async (resolve, reject) => {\n try {\n const config = this.paymentIntegrationService.getState().getStoreConfig();\n const bigpayBaseUrl = config?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this.paymentIntegrationService.createHostedForm(\n bigpayBaseUrl,\n formOptions\n );\n\n await form.attach();\n\n resolve(form);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n private isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n\n return !!options.form?.fields;\n }\n\n private processAdditionalAction(error: any): Promise {\n if (!isRequestError(error)) {\n return Promise.reject(error);\n }\n\n if (some(error.body.errors, {code: 'additional_action_required'})) {\n const { additional_action_required: { data : { redirect_url } } } = error.body;\n\n return new Promise(() => window.location.replace(redirect_url));\n }\n\n return Promise.reject(error);\n }\n\n private getInitializeOptions(): MolliePaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private loadMollieJs(merchantId: string, locale: string, testmode = false): Promise {\n if (this.mollieClient) {\n return Promise.resolve(this.mollieClient);\n }\n\n return this.mollieScriptLoader\n .load(merchantId, locale, testmode);\n }\n\n private getMollieClient(): MollieClient {\n if (!this.mollieClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.mollieClient;\n }\n\n private getShopperLocale(): string {\n if (!this.locale) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.locale;\n }\n\n /**\n * ContainerId is use in Mollie for determined either its showing or not the\n * container, because when Mollie has Vaulted Instruments it gets hide,\n * and shows an error because can't mount Provider Components\n *\n * We had to add a settimeout because Mollie sets de tab index after mounting\n * each component, but without a setTimeOut Mollie is not able to find the\n * components as they are hidden so we need to wait until they are shown\n */\n private mountElements() {\n const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this.getInitializeOptions();\n let container: HTMLElement | null;\n\n if (containerId) {\n container = document.getElementById(containerId);\n }\n\n setTimeout(() => {\n if (!containerId || container?.style.display !== 'none') {\n const mollieClient = this.getMollieClient();\n\n this.cardHolderElement = mollieClient.createComponent('cardHolder', { styles });\n this.cardHolderElement.mount(`#${cardHolderId}`);\n\n this.cardNumberElement = mollieClient.createComponent('cardNumber', { styles });\n this.cardNumberElement.mount(`#${cardNumberId}`);\n\n this.verificationCodeElement = mollieClient.createComponent('verificationCode', { styles });\n this.verificationCodeElement.mount(`#${cardCvcId}`);\n\n this.expiryDateElement = mollieClient.createComponent('expiryDate', { styles });\n this.expiryDateElement.mount(`#${cardExpiryId}`);\n }\n }, 0);\n }\n\n private loadPaymentMethodsAllowed(mollie: MolliePaymentInitializeOptions, methodId: string, gatewayId: string){\n if (methodsNotAllowedWhenDigitalOrder.includes(methodId)) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const cartDigitalItems = cart.lineItems?.digitalItems;\n\n if (cartDigitalItems && cartDigitalItems.length > 0) {\n const { containerId } = this.getInitializeOptions();\n\n if (containerId) {\n const container = document.getElementById(containerId);\n\n if (container) {\n const paragraph = document.createElement('p') ;\n paragraph.setAttribute(\"id\",`${gatewayId}-${methodId}-paragraph`)\n\n if (mollie.unsupportedMethodMessage) {\n paragraph.innerText = mollie.unsupportedMethodMessage;\n container.appendChild(paragraph);\n mollie.disableButton(true);\n }\n }\n }\n }\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isMollieWindow from './is-mollie-window';\nimport { MollieClient } from './mollie';\n\nexport default class MollieScriptLoader {\n constructor(private scriptLoader: ScriptLoader, private mollieHostWindow: Window = window) {}\n\n async load(merchantId: string, locale: string, testmode: boolean): Promise {\n await this.scriptLoader.loadScript('https://js.mollie.com/v1/mollie.js');\n\n if (!isMollieWindow(this.mollieHostWindow)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.mollieHostWindow.Mollie(merchantId, {\n locale,\n testmode,\n });\n }\n}\n","import { MollieHostWindow } from './mollie';\n\nexport default function isMollieWindow(window: Window): window is MollieHostWindow {\n return 'Mollie' in window;\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MolliePaymentStrategy from './mollie-payment-strategy';\nimport MollieScriptLoader from './mollie-script-loader';\n\nconst createMolliePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new MolliePaymentStrategy(\n new MollieScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n );\n};\n\nexport default toResolvableModule(createMolliePaymentStrategy, [\n { gateway: 'mollie' },\n { gateway: 'mollie', id: 'applepay' },\n]);\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { isEmpty, map, omitBy } from 'lodash';\n\nimport {\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MonerisStylingProps, {\n MoneriesHostedFieldsQueryParams,\n MonerisInitializationData,\n MonerisResponseData,\n} from './moneris';\nimport MonerisPaymentInitializeOptions, {\n WithMonerisPaymentInitializeOptions,\n} from './moneris-payment-initialize-options';\n\nconst IFRAME_NAME = 'moneris-payment-iframe';\nconst RESPONSE_SUCCESS_CODE = '001';\n\nexport default class MonerisPaymentStrategy {\n private iframe?: HTMLIFrameElement;\n private initializeOptions?: MonerisPaymentInitializeOptions;\n private windowEventListener?: (response: MessageEvent) => void;\n\n private hostedForm?: HostedForm;\n constructor(private paymentIntegrationService: PaymentIntegrationService) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithMonerisPaymentInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n\n const { moneris: monerisOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" argument is not provided.',\n );\n }\n\n if (!monerisOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.moneris\" argument is not provided.',\n );\n }\n\n this.initializeOptions = monerisOptions;\n\n const { config, initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!initializationData?.profileId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (monerisOptions.form && this.shouldShowTSVHostedForm(methodId)) {\n this.hostedForm = await this.mountCardVerificationfields(monerisOptions.form);\n }\n\n if (!this.iframe) {\n this.iframe = this.createIframe(\n monerisOptions.containerId,\n initializationData,\n !!config.testMode,\n );\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentInitializeOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n await this.executeWithVaulted(payment);\n\n return;\n }\n\n return this.executeWithCC(payment);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n if (this.windowEventListener) {\n window.removeEventListener('message', this.windowEventListener);\n this.windowEventListener = undefined;\n }\n\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n this.iframe = undefined;\n }\n\n return Promise.resolve();\n }\n\n private async executeWithCC(payment: OrderPaymentRequestBody): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(payment.methodId);\n\n const testMode = paymentMethod.config.testMode;\n const paymentData = payment.paymentData || {};\n const instrumentSettings = isHostedInstrumentLike(paymentData)\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = instrumentSettings;\n\n const nonce = await new Promise((resolve, reject) => {\n if (!this.iframe) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const frameref: Window | null = this.iframe.contentWindow;\n\n if (frameref === null) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n frameref.postMessage('tokenize', this.monerisURL(!!testMode));\n\n this.windowEventListener = (response: MessageEvent) => {\n if (typeof response.data !== 'string') {\n return;\n }\n\n try {\n resolve(this.handleMonerisResponse(response));\n } catch (error) {\n reject(error);\n }\n };\n\n window.addEventListener('message', this.windowEventListener);\n });\n\n if (nonce !== undefined) {\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: { nonce, shouldSaveInstrument, shouldSetAsDefaultInstrument },\n });\n }\n }\n\n private async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this.hostedForm) {\n const form = this.hostedForm;\n\n await form.validate();\n await form.submit(payment);\n\n return this.paymentIntegrationService.loadCurrentOrder();\n }\n\n return this.paymentIntegrationService.submitPayment(payment);\n }\n\n private shouldShowTSVHostedForm(methodId: string): boolean {\n return this.isHostedPaymentFormEnabled(methodId) && this.isHostedFieldAvailable();\n }\n\n private isHostedPaymentFormEnabled(methodId: string): boolean {\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private getInitializeOptions(): MonerisPaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private async mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n const bigpayBaseUrl = this.paymentIntegrationService.getState().getStoreConfig()\n ?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this.paymentIntegrationService.createHostedForm(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private createIframe(\n containerId: string,\n initializationData: MonerisInitializationData,\n testMode: boolean,\n style?: MonerisStylingProps,\n ): HTMLIFrameElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError('Unable to create iframe without valid container ID.');\n }\n\n const iframe: HTMLIFrameElement = document.createElement('iframe');\n const monerisQueryParams: MoneriesHostedFieldsQueryParams = {\n id: initializationData.profileId,\n pmmsg: true,\n display_labels: 1,\n enable_exp: 1,\n enable_cvd: 1,\n css_body:\n style?.cssBody ||\n 'font-family: Arial, Helvetica,sans-serif;background: transparent;',\n css_textbox:\n style?.cssTextbox ||\n 'border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;',\n css_textbox_pan: style?.cssTextboxCardNumber || 'width: 240px;',\n css_textbox_exp:\n style?.cssTextboxExpiryDate || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_textbox_cvd: style?.cssTextboxCVV || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_input_label:\n style?.cssInputLabel ||\n 'font-size: 10px;position: relative;top: 8px;left: 6px;background: rgb(255,255,255);padding: 3px 2px;color: rgb(66,66,66);font-weight: 600;z-index: 2;',\n pan_label: initializationData.creditCardLabel || 'Credit Card Number',\n exp_label: initializationData.expiryDateLabel || 'Expiration',\n cvd_label: initializationData.cvdLabel || 'CVD',\n };\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const queryString = map(monerisQueryParams, (value, key) => `${key}=${value}`).join('&');\n\n iframe.width = '100%';\n iframe.height = '100%';\n iframe.name = IFRAME_NAME;\n iframe.id = IFRAME_NAME;\n iframe.style.border = 'none';\n iframe.src = `${this.monerisURL(testMode)}?${queryString}`;\n\n container.appendChild(iframe);\n\n return iframe;\n }\n\n private handleMonerisResponse(response: MessageEvent): string {\n const monerisResponse: MonerisResponseData = JSON.parse(response.data);\n\n if (monerisResponse.responseCode[0] !== RESPONSE_SUCCESS_CODE) {\n throw new Error(monerisResponse.errorMessage);\n }\n\n return monerisResponse.dataKey;\n }\n\n private monerisURL(testMode: boolean): string {\n return `https://${testMode ? 'esqa' : 'www3'}.moneris.com/HPPtoken/index.php`;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport MonerisPaymentStrategy from './moneris-payment-strategy';\n\nconst createMonerisPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new MonerisPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createMonerisPaymentStrategy, [{ id: 'moneris' }]);\n","import { omit } from 'lodash';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class NoPaymentDataRequiredPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(omit(payload, 'payment'), options);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport NoPaymentDataRequiredPaymentStrategy from './no-payment-data-required-strategy';\n\nconst createNoPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new NoPaymentDataRequiredPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createNoPaymentStrategy, [{ id: 'nopaymentdatarequired' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OfflinePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment ? { methodId: payload.payment.methodId } : undefined,\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OfflinePaymentStrategy from './offline-payment-strategy';\n\nconst createOfflinePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OfflinePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOfflinePaymentStrategy, [{ type: 'PAYMENT_TYPE_OFFLINE' }]);\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OffsitePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const orderPayload = this._shouldSubmitFullPayload(payment) ? payload : order;\n const paymentData = payment && payment.paymentData;\n const instrumentId =\n (paymentData && isVaultedInstrument(paymentData) && paymentData.instrumentId) ||\n undefined;\n const shouldSaveInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSaveInstrument) ||\n undefined;\n const shouldSetAsDefaultInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSetAsDefaultInstrument) ||\n undefined;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n await this._paymentIntegrationService.submitOrder(orderPayload, options);\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId,\n gatewayId,\n instrumentId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _shouldSubmitFullPayload(payment?: OrderPaymentRequestBody): boolean {\n // FIXME: A temporary workaround to support offsite payment methods\n // where their return URL needs to be provided by the core app.\n if (!payment) {\n return false;\n }\n\n return (\n payment.gatewayId === 'adyen' ||\n payment.gatewayId === 'barclaycard' ||\n payment.methodId === 'ccavenuemars'\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OffsitePaymentStrategy from './offsite-payment-strategy';\n\nconst createOffsitePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OffsitePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOffsitePaymentStrategy, [{ type: 'PAYMENT_TYPE_HOSTED' }]);\n","export const LOADING_INDICATOR_STYLES = {\n 'background-color': 'rgba(0, 0, 0, 0.4)',\n 'z-index': '1000',\n};\n","import {\n HostedInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentInstrumentPayload,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { isPaypalCommerceProviderError } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommercePaymentInitializeOptions, {\n WithPayPalCommercePaymentInitializeOptions,\n} from './paypal-commerce-payment-initialize-options';\n\nexport default class PayPalCommercePaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalcommerce?: PayPalCommercePaymentInitializeOptions;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommercePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce } = options || {};\n\n this.paypalcommerce = paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.loadingIndicatorContainer = paypalcommerce.container.split('#')[1];\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n if (paypalcommerce.onInit && typeof paypalcommerce.onInit === 'function') {\n paypalcommerce.onInit(() => this.renderButton(methodId, paypalcommerce));\n }\n\n if (\n paypalcommerce.shouldRenderPayPalButtonOnInitialization === undefined ||\n paypalcommerce.shouldRenderPayPalButtonOnInitialization\n ) {\n this.renderButton(methodId, paypalcommerce);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { onError } = this.paypalcommerce || {};\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n const shouldHandleInstrumentDeclinedError =\n features && features['PAYPAL-3438.handling_instrument_declined_error_ppc'];\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, paymentData } = payment;\n\n if (this.isPayPalVaultedInstrumentPaymentData(paymentData) && !this.orderId) {\n this.orderId = await this.createOrder();\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n const paymentPayload = this.isPayPalVaultedInstrumentPaymentData(paymentData)\n ? this.prepareVaultedInstrumentPaymentPayload(methodId, this.orderId, paymentData)\n : this.preparePaymentPayload(methodId, this.orderId, paymentData);\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error: unknown) {\n if (this.isProviderError(error) && shouldHandleInstrumentDeclinedError) {\n await this.paypalCommerceIntegrationService.loadPayPalSdk(payment.methodId);\n\n await new Promise((_resolve, reject) => {\n if (this.paypalcommerce) {\n this.paypalButton?.close();\n this.renderButton(payment.methodId, this.paypalcommerce);\n this.handleError(new Error('INSTRUMENT_DECLINED'), onError);\n }\n\n reject();\n });\n }\n\n this.handleError(error, onError);\n\n return Promise.reject();\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n private prepareVaultedInstrumentPaymentPayload(\n methodId: string,\n paypalOrderId: string,\n paymentData: VaultedInstrument & HostedInstrument,\n ): Payment {\n const { instrumentId, shouldSetAsDefaultInstrument } = paymentData;\n\n const shouldConfirmInstrument = !this.isTrustedVaultingFlow(paymentData);\n\n if (shouldConfirmInstrument) {\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument: shouldConfirmInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n },\n },\n };\n }\n\n return {\n methodId,\n paymentData: {\n instrumentId,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n bigpay_token: {\n token: instrumentId,\n },\n },\n },\n };\n }\n\n private preparePaymentPayload(\n methodId: string,\n paypalOrderId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n ): Payment {\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_account: {\n order_id: paypalOrderId,\n },\n },\n },\n };\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommercePaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () => this.createOrder(),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onError: (error) => this.handleError(error, onError),\n onCancel: () => this.toggleLoadingIndicator(false),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommercePaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommercePaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleError(\n error: unknown,\n onError: PayPalCommercePaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n private async createOrder(): Promise {\n const fieldsValues = this.getFieldsValues();\n\n return this.paypalCommerceIntegrationService.createOrder('paypalcommercecheckout', {\n shouldSaveInstrument: fieldsValues?.shouldSaveInstrument || false,\n });\n }\n\n /**\n *\n * Vaulting flow methods\n *\n * */\n private getFieldsValues(): HostedInstrument | undefined {\n const { getFieldsValues } = this.paypalcommerce || {};\n\n return typeof getFieldsValues === 'function' ? getFieldsValues() : undefined;\n }\n\n private isTrustedVaultingFlow(paymentData?: PaymentInstrumentPayload): boolean {\n if (paymentData && isVaultedInstrument(paymentData)) {\n const state = this.paymentIntegrationService.getState();\n\n const instruments = state.getInstruments();\n\n const { trustedShippingAddress } =\n instruments?.find(({ bigpayToken }) => bigpayToken === paymentData.instrumentId) ||\n {};\n\n return !!trustedShippingAddress;\n }\n\n return false;\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Guards\n *\n */\n private isPayPalVaultedInstrumentPaymentData(\n paymentData?: PaymentInstrumentPayload,\n ): paymentData is VaultedInstrument & HostedInstrument {\n return (\n !!paymentData && isVaultedInstrument(paymentData) && isHostedInstrumentLike(paymentData)\n );\n }\n\n private isProviderError(error: unknown): boolean {\n if (isPaypalCommerceProviderError(error)) {\n const paypalProviderError = error?.errors?.filter((e) => e.provider_error) || [];\n\n return paypalProviderError[0]?.provider_error?.code === 'INSTRUMENT_DECLINED';\n }\n\n return false;\n }\n}\n","export interface ProviderError extends Error {\n errors?: ErrorElement[];\n status?: string;\n three_ds_result?: {\n acs_url: unknown;\n payer_auth_request: unknown;\n merchant_data: unknown;\n callback_url: unknown;\n };\n}\n\nexport interface ErrorElement {\n code: string;\n message: string;\n provider_error?: {\n code: string;\n };\n}\n\nexport default function isPaypalCommerceProviderError(error: unknown): error is ProviderError {\n return typeof error === 'object' && error !== null && 'errors' in error;\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\n","import { MessagesStyleOptions, PayPalBNPLConfigurationItem } from '../paypal-commerce-types';\n\nfunction getPaypalMessagesStylesFromBNPLConfig({\n styles,\n}: PayPalBNPLConfigurationItem): MessagesStyleOptions {\n const messagesStyles: MessagesStyleOptions = {};\n\n if (styles.color) {\n messagesStyles.color = styles.color;\n }\n\n if (styles.layout) {\n messagesStyles.layout = styles.layout;\n }\n\n if (styles['logo-type'] || styles['logo-position']) {\n messagesStyles.logo = {};\n\n if (styles['logo-type']) {\n messagesStyles.logo.type = styles['logo-type'];\n }\n\n if (styles['logo-position']) {\n messagesStyles.logo.position = styles['logo-position'];\n }\n }\n\n if (styles.ratio) {\n messagesStyles.ratio = styles.ratio;\n }\n\n if (styles['text-color'] || styles['text-size']) {\n messagesStyles.text = {};\n\n if (styles['text-color']) {\n messagesStyles.text.color = styles['text-color'];\n }\n\n if (styles['text-size']) {\n messagesStyles.text.size = +styles['text-size'];\n }\n }\n\n return messagesStyles;\n}\n\nexport default getPaypalMessagesStylesFromBNPLConfig;\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalMessagesSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditPaymentInitializeOptions, {\n WithPayPalCommerceCreditPaymentInitializeOptions,\n} from './paypal-commerce-credit-payment-initialize-options';\n\nexport default class PayPalCommerceCreditPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private paypalCommerceSdk: PayPalCommerceSdk,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceCreditPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercecredit } = options || {};\n\n const paypalOptions = paypalcommercecredit || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n // TODO: update paypalBNPLConfiguration with empty array as default value when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const { paypalBNPLConfiguration, orderId } = paymentMethod.initializationData || {};\n const { bannerContainerId = '', container } = paypalOptions;\n\n // TODO: remove paypalBNPLConfiguration check when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n if (paypalBNPLConfiguration && document.getElementById(bannerContainerId)) {\n const bannerConfiguration = paypalBNPLConfiguration.find(({ id }) => id === 'checkout');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n const paypalMessages = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId, bannerConfiguration);\n }\n\n // TODO: this condition can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n if (document.getElementById(bannerContainerId)) {\n const paypalMessages = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n return this.renderMessages(paypalMessages, bannerContainerId);\n }\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = container?.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalOptions: PayPalCommerceCreditPaymentInitializeOptions,\n ): void {\n if (!paypalOptions?.container) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"container\" argument is not provided.',\n );\n }\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalOptions;\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcheckout',\n ),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.PAYLATER) {\n return;\n }\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.CREDIT) {\n throw new NotImplementedError(\n `PayPal ${fundingSource} is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceCreditPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n if (onValidate && typeof onValidate === 'function') {\n await onValidate(onValidationPassed, reject);\n }\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceCreditPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n if (submitForm && typeof submitForm === 'function') {\n submitForm();\n }\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceCreditPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Render Pay Later Messages\n *\n * */\n private renderMessages(\n paypalMessages: PayPalMessagesSdk,\n bannerContainerId: string,\n bannerConfiguration?: PayPalBNPLConfigurationItem, // TODO: this should not be optional when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n const grandTotal = checkout.outstandingBalance;\n // TODO: default style can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const style = bannerConfiguration\n ? getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration)\n : {\n layout: 'text',\n logo: {\n type: 'inline',\n },\n };\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: grandTotal,\n placement: 'payment',\n style,\n };\n\n paypalMessages.Messages(paypalMessagesOptions).render(`#${bannerContainerId}`);\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n createPayPalCommerceSdk(),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditPaymentStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoPaymentInitializeOptions, {\n WithPayPalCommerceVenmoPaymentInitializeOptions,\n} from './paypal-commerce-venmo-payment-initialize-options';\n\nexport default class PayPalCommerceVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercevenmo } = options || {};\n\n const paypalOptions = paypalcommercevenmo || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { paymentButtonStyles } = paymentMethod.initializationData || {};\n const { checkoutPaymentButtonStyles } = paymentButtonStyles || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommercevenmo;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(\n checkoutPaymentButtonStyles,\n ),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmocheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n throw new NotImplementedError(\n `PayPal Venmo is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceVenmoPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceVenmoPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { PayPalApmSdk, PayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private paypalApms?: PayPalApmSdk;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const {\n gatewayId,\n methodId,\n paypalcommerce, // FIXME: this option is deprecated\n paypalcommercealternativemethods,\n } = options;\n const paypalOptions = paypalcommercealternativemethods || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { orderId, shouldRenderFields } = paymentMethod.initializationData || {};\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n this.paypalApms = await this.paypalCommerceSdk.getPayPalApmsSdk(\n paymentMethod,\n state.getCartOrThrow().currency.code,\n );\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, paypalOptions);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, paypalOptions);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paypalCommerceIntegrationService.submitPayment(\n methodId,\n this.orderId,\n gatewayId,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalAmpsSdk = this.getPaypalAmpsSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, submitForm } = paypalOptions;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: methodId,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n onInit: (_, actions) => paypalOptions.onInitButton(actions),\n createOrder: () => this.onCreateOrder(methodId, gatewayId, paypalOptions),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleFailure(error, onError),\n onClick: async (_, actions) =>\n paypalOptions.onValidate(actions.resolve, actions.reject),\n };\n\n this.paypalButton = paypalAmpsSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async onCreateOrder(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): Promise {\n const { onValidate } = paypalOptions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return () => Promise.resolve();\n };\n\n await onValidate(onValidationPassed, noop);\n\n const orderId = await this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n );\n\n if (this.isNonInstantPaymentMethod(methodId)) {\n const order = { useStoreCredit: false };\n const options = {\n params: {\n methodId,\n gatewayId,\n },\n };\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(methodId, orderId, gatewayId);\n }\n\n return orderId;\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceAlternativeMethodsPaymentOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n }\n\n private handleFailure(\n error: Error,\n onError: PayPalCommerceAlternativeMethodsPaymentOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Fields methods\n *\n * */\n private renderFields(\n methodId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalAmpsSdk = this.getPaypalAmpsSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const { firstName, lastName, email } = state.getBillingAddressOrThrow();\n\n const { apmFieldsContainer, apmFieldsStyles } = paypalOptions;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument should contain \"apmFieldsContainer\".',\n );\n }\n\n const fieldContainerElement = document.querySelector(apmFieldsContainer);\n\n if (fieldContainerElement) {\n fieldContainerElement.innerHTML = '';\n }\n\n const fieldsOptions = {\n fundingSource: methodId,\n style: apmFieldsStyles || {},\n fields: {\n name: {\n value: `${firstName} ${lastName}`,\n },\n email: {\n value: email,\n },\n },\n };\n\n const paypalPaymentFields = paypalAmpsSdk.PaymentFields(fieldsOptions);\n\n paypalPaymentFields.render(apmFieldsContainer);\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantAlternativePaymentMethods;\n }\n\n private getPaypalAmpsSdkOrThrow() {\n if (!this.paypalApms) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalApms;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PayPalCommerceAlternativeMethodsPaymentStrategy from './paypal-commerce-alternative-methods-payment-strategy';\n\nconst createPayPalCommerceAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n new LoadingIndicator({\n containerStyles: LOADING_INDICATOR_STYLES,\n }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\n]);\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumber in fields &&\n HostedFieldType.CardName in fields &&\n HostedFieldType.CardExpiry in fields\n );\n}\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardVaultedFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumberVerification in fields &&\n HostedFieldType.CardCodeVerification in fields &&\n HostedFieldType.CardExpiryVerification in fields\n );\n}\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isPayPalCommerceAcceleratedCheckoutCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport {\n HostedCardFieldOptions,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldStylesMap,\n HostedFieldType,\n HostedFieldValidateEventData,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInstrument,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n isCreditCardFormFields,\n isCreditCardVaultedFormFields,\n isHostedInstrumentLike,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n isPayPalCommerceAcceleratedCheckoutCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n LiabilityShiftEnum,\n PayPalCommerceCardFields,\n PayPalCommerceCardFieldsConfig,\n PayPalCommerceCardFieldsOnApproveData,\n PayPalCommerceCardFieldsState,\n PayPalCommerceFields,\n PayPalCommerceHostedFieldsRenderOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCardsPaymentInitializeOptions, {\n WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n} from './paypal-commerce-credit-cards-payment-initialize-options';\n\nexport default class PayPalCommerceCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private isCreditCardVaultedForm?: boolean;\n\n private cardFields?: PayPalCommerceCardFields;\n private cvvField?: PayPalCommerceFields;\n private expiryField?: PayPalCommerceFields;\n private numberField?: PayPalCommerceFields;\n private nameField?: PayPalCommerceFields;\n\n private hostedFormOptions?: HostedFormOptions;\n private returnedOrderId?: string;\n private returnedVaultedToken?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercecreditcards, paypalcommerce } = options;\n const paypalCommerceInitializationOptions = paypalcommercecreditcards || paypalcommerce;\n\n const { form, onCreditCardFieldsRenderingError } =\n paypalCommerceInitializationOptions || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!form) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form\" argument is not provided.',\n );\n }\n\n this.hostedFormOptions = form;\n\n this.isCreditCardForm = isCreditCardFormFields(form.fields);\n this.isCreditCardVaultedForm =\n isCreditCardVaultedFormFields(form.fields) && !this.hasUndefinedValues();\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, undefined, true, true);\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.initializeFields(form, onCreditCardFieldsRenderingError);\n }\n\n if (this.shouldInitializePayPalFastlane(methodId)) {\n await this.initializePayPalFastlaneOrThrow(methodId);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n\n if (!payment || !methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.executionPaymentData = paymentData;\n\n if (this.isCreditCardForm || this.isCreditCardVaultedForm) {\n await this.validateHostedFormOrThrow();\n await this.submitHostedForm();\n } else {\n // This condition is triggered when we pay with vaulted instrument and shipping address is truste\n const { orderId } = await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n );\n\n this.returnedOrderId = orderId;\n }\n\n const submitPaymentPayload = this.preparePaymentPayload(\n methodId,\n paymentData,\n this.returnedOrderId,\n this.returnedVaultedToken,\n );\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this.cvvField?.close();\n await this.expiryField?.close();\n await this.numberField?.close();\n await this.nameField?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Submit Payment Payload preparing method\n *\n * `vaultedToken` is used when we pay with vaulted instrument (with trusted shipping address and untrusted)\n * `setupToken` is used when we pay with vaulted instrument (untrusted shipping address)\n * `orderId` is used in every case (basic card payment, trusted shipping address and untrusted)\n */\n private preparePaymentPayload(\n methodId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n orderId?: string,\n nonce?: string,\n ): Payment {\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const instrumentId =\n paymentData && isVaultedInstrument(paymentData) ? paymentData.instrumentId : undefined;\n\n const bigpay_token = omitBy(\n {\n verification_nonce: nonce,\n token: instrumentId,\n },\n isNil,\n );\n\n return {\n methodId,\n paymentData: {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n instrumentId,\n formattedPayload: {\n ...(nonce || instrumentId ? { bigpay_token } : {}),\n ...(orderId ? { card_with_order: { order_id: orderId } } : {}),\n },\n },\n };\n }\n\n /**\n *\n * Card fields initialize\n *\n */\n private async initializeFields(\n formOptions: HostedFormOptions,\n onCreditCardFieldsRenderingError?: PayPalCommerceCreditCardsPaymentInitializeOptions['onCreditCardFieldsRenderingError'],\n ): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const executeCallback = this.getExecuteCallback(fields);\n const state = this.paymentIntegrationService.getState();\n const features = state.getStoreConfigOrThrow().checkoutSettings.features;\n\n const cardFieldsConfig: PayPalCommerceCardFieldsConfig = {\n style: this.getInputStyles(styles),\n onApprove: ({\n orderID,\n vaultSetupToken,\n liabilityShift,\n }: PayPalCommerceCardFieldsOnApproveData) => {\n if (\n features?.['PAYPAL-4591.paypal_commerce_3ds_verification'] &&\n (liabilityShift === LiabilityShiftEnum.No ||\n liabilityShift === LiabilityShiftEnum.Unknown)\n ) {\n throw new Error();\n }\n\n return this.handleApprove({ orderID, vaultSetupToken });\n },\n onError: () => {\n throw new PaymentMethodFailedError();\n },\n inputEvents: {\n onChange: (event) => this.onChangeHandler(formOptions, event),\n onFocus: (event) => this.onFocusHandler(formOptions, event),\n onBlur: (event) => this.onBlurHandler(formOptions, event),\n onInputSubmitRequest: (event) => this.onInputSubmitRequest(formOptions, event),\n },\n ...executeCallback,\n };\n\n this.cardFields = await paypalSdk.CardFields(cardFieldsConfig);\n\n if (!this.cardFields.isEligible()) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n this.stylizeInputContainers(fields);\n\n if (isCreditCardFormFields(fields)) {\n await this.renderFields(fields);\n }\n\n if (isCreditCardVaultedFormFields(fields)) {\n await this.renderVaultedFields(fields);\n }\n } catch (error: unknown) {\n if (typeof onCreditCardFieldsRenderingError === 'function') {\n onCreditCardFieldsRenderingError(error);\n }\n }\n }\n\n /**\n *\n * Get execute callback method\n * Depends on shipping address is trusted or not we should pass to PP\n * `createVaultSetupToken` callback if address is untrusted or\n * `createOrder` if address is trusted\n *\n */\n private getExecuteCallback(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ) {\n const isVaultedForm = isCreditCardVaultedFormFields(fields);\n\n return isVaultedForm ? this.createVaultSetupTokenCallback() : this.createOrderCallback();\n }\n\n private createVaultSetupTokenCallback() {\n return {\n createVaultSetupToken: async () => {\n const { setupToken } =\n (await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n {\n ...this.getInstrumentParams(),\n setupToken: true,\n },\n )) || {};\n\n return setupToken;\n },\n };\n }\n\n private createOrderCallback() {\n return {\n createOrder: async () => {\n const { orderId } =\n (await this.paypalCommerceIntegrationService.createOrderCardFields(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n )) || {};\n\n return orderId;\n },\n };\n }\n\n /**\n *\n * onApprove method\n * When submitting a form with a `submitHostedForm` method if there is no error\n * then onApprove callback is triggered and depends on the flow\n * we will receive an `orderID` if it's basic paying and `vaultSetupToken` if we are paying\n * with vaulted instrument and shipping address is untrusted\n *\n */\n private handleApprove({ orderID, vaultSetupToken }: PayPalCommerceCardFieldsOnApproveData) {\n if (orderID) {\n this.returnedOrderId = orderID;\n }\n\n if (vaultSetupToken) {\n this.returnedVaultedToken = vaultSetupToken;\n }\n }\n\n /**\n *\n * Rendering Card Fields methods\n *\n */\n private async renderFields(fieldsOptions: HostedCardFieldOptionsMap) {\n const cardFields = this.getCardFieldsOrThrow();\n\n if (fieldsOptions.cardCode?.containerId) {\n this.cvvField = cardFields.CVVField({\n placeholder: '',\n });\n await this.cvvField.render(`#${fieldsOptions.cardCode.containerId}`);\n }\n\n if (fieldsOptions.cardExpiry?.containerId) {\n this.expiryField = cardFields.ExpiryField();\n await this.expiryField.render(`#${fieldsOptions.cardExpiry.containerId}`);\n }\n\n if (fieldsOptions.cardName?.containerId) {\n this.nameField = cardFields.NameField({\n placeholder: '',\n });\n await this.nameField.render(`#${fieldsOptions.cardName.containerId}`);\n }\n\n if (fieldsOptions.cardNumber?.containerId) {\n this.numberField = cardFields.NumberField({\n placeholder: '',\n });\n await this.numberField.render(`#${fieldsOptions.cardNumber.containerId}`);\n }\n }\n\n private async renderVaultedFields(fieldsOptions: HostedStoredCardFieldOptionsMap) {\n const cardFields = this.getCardFieldsOrThrow();\n\n if (fieldsOptions.cardCodeVerification?.containerId) {\n this.cvvField = cardFields.CVVField({\n placeholder: '',\n });\n await this.cvvField.render(`#${fieldsOptions.cardCodeVerification.containerId}`);\n }\n\n if (fieldsOptions.cardExpiryVerification?.containerId) {\n this.expiryField = cardFields.ExpiryField();\n await this.expiryField.render(`#${fieldsOptions.cardExpiryVerification.containerId}`);\n }\n\n if (fieldsOptions.cardNumberVerification?.containerId) {\n this.numberField = cardFields.NumberField({\n placeholder: '',\n });\n await this.numberField.render(`#${fieldsOptions.cardNumberVerification.containerId}`);\n }\n }\n\n /**\n *\n * Instrument params method\n *\n */\n private getInstrumentParams(): HostedInstrument | VaultedInstrument {\n if (!this.executionPaymentData) {\n return {};\n }\n\n if (isHostedInstrumentLike(this.executionPaymentData)) {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } =\n this.executionPaymentData;\n\n return {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n if (isVaultedInstrument(this.executionPaymentData)) {\n const { instrumentId } = this.executionPaymentData;\n\n return {\n instrumentId,\n };\n }\n\n return {};\n }\n\n private getFieldTypeByEmittedField({\n emittedBy,\n }: PayPalCommerceCardFieldsState):\n | HostedFieldBlurEventData\n | HostedFieldEnterEventData\n | HostedFieldFocusEventData {\n return {\n fieldType: this.mapFieldType(emittedBy),\n };\n }\n\n /**\n *\n * Form submit method\n * Triggers a form submit\n * */\n private async submitHostedForm() {\n const cardFields = this.getCardFieldsOrThrow();\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const submitConfig = {\n billingAddress: {\n company: billingAddress.company,\n addressLine1: billingAddress.address1,\n addressLine2: billingAddress.address2,\n adminArea1: billingAddress.stateOrProvinceCode,\n adminArea2: billingAddress.city,\n postalCode: billingAddress.postalCode,\n countryCode: billingAddress.countryCode,\n },\n };\n\n try {\n if (this.isCreditCardVaultedForm) {\n await cardFields.submit();\n } else {\n await cardFields.submit(submitConfig);\n }\n } catch (_) {\n throw new PaymentMethodFailedError(\n 'Failed authentication. Please try to authorize again.',\n );\n }\n }\n\n /**\n *\n * Validation and errors\n *\n */\n private async validateHostedFormOrThrow() {\n const cardFields = this.getCardFieldsOrThrow();\n const cardFieldsState = await cardFields.getState().then((data) => data);\n const validationData = this.getValidityData(cardFieldsState);\n\n if (validationData.isValid) {\n return;\n }\n\n this.hostedFormOptions?.onValidate?.(validationData);\n\n throw new PaymentInvalidFormError(this.mapValidationErrors(validationData.errors));\n }\n\n private getValidityData({\n fields,\n }: PayPalCommerceCardFieldsState): HostedFieldValidateEventData {\n const updatedFields = { ...fields };\n\n delete updatedFields.cardNameField;\n\n const fieldsKeys = Object.keys(updatedFields) as Array<\n keyof PayPalCommerceCardFieldsState['fields']\n >;\n\n const isValid = fieldsKeys.every((key) => updatedFields[key]?.isValid);\n\n const errors = fieldsKeys.reduce((fieldsErrors, key) => {\n const fieldType = this.mapFieldType(key);\n\n return {\n ...fieldsErrors,\n [fieldType]: updatedFields[key]?.isValid\n ? undefined\n : [this.getInvalidErrorByFieldType(fieldType)],\n };\n }, {});\n\n return { isValid, errors };\n }\n\n private getInvalidErrorByFieldType(fieldType: string): HostedInputValidateErrorData {\n switch (fieldType) {\n case HostedFieldType.CardCode:\n case HostedFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case HostedFieldType.CardNumber:\n case HostedFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case HostedFieldType.CardExpiry:\n case HostedFieldType.CardExpiryVerification:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private mapValidationErrors(\n validationErrors: HostedInputValidateErrorDataMap = {},\n ): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n const validationErrorsKeys = Object.keys(validationErrors) as Array<\n keyof HostedInputValidateErrorDataMap\n >;\n\n validationErrorsKeys.forEach((key) => {\n errors[key] = [\n {\n message: validationErrors[key]?.[0]?.message || '',\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n /**\n *\n * Fields mappers\n *\n */\n private mapFieldType(type: string): HostedFieldType {\n switch (type) {\n case 'name':\n return HostedFieldType.CardName;\n\n case 'cardNumberField':\n case 'number':\n return this.isCreditCardForm\n ? HostedFieldType.CardNumber\n : HostedFieldType.CardNumberVerification;\n\n case 'cardExpiryField':\n case 'expiry':\n return this.isCreditCardForm\n ? HostedFieldType.CardExpiry\n : HostedFieldType.CardExpiryVerification;\n\n case 'cardCvvField':\n case 'cvv':\n return this.isCreditCardForm\n ? HostedFieldType.CardCode\n : HostedFieldType.CardCodeVerification;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n /**\n *\n * Utils\n *\n */\n private getCardFieldsOrThrow(): PayPalCommerceCardFields {\n if (!this.cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.cardFields;\n }\n\n private getInputStyles(\n styles?: HostedFieldStylesMap,\n ): PayPalCommerceHostedFieldsRenderOptions['styles'] {\n const commonStyles = {\n 'font-size': styles?.default?.fontSize || '1rem',\n 'font-family':\n styles?.default?.fontFamily || 'Montserrat, Arial, Helvetica, sans-serif',\n 'font-weight': styles?.default?.fontWeight || '400',\n outline: 'none',\n padding: '9px 13px',\n };\n\n const defaultStyles = { ...commonStyles, color: '#333333' };\n const errorStyles = { ...commonStyles, color: 'red' };\n\n return {\n input: defaultStyles,\n '.invalid': errorStyles,\n '.valid': defaultStyles,\n ':focus': defaultStyles,\n };\n }\n\n private stylizeInputContainers(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ): void {\n Object.values(fields || {}).forEach((id: HostedCardFieldOptions) => {\n const element = document.getElementById(`${id?.containerId || ''}`);\n\n if (element) {\n element.style.padding = '0px';\n element.style.boxShadow = 'none';\n element.style.border = 'none';\n element.style.background = 'transparent';\n element.style.marginBottom = '10px';\n element.style.marginLeft = '-5px';\n }\n });\n }\n\n private hasUndefinedValues() {\n if (this.hostedFormOptions) {\n return Object.values(this.hostedFormOptions.fields).some(\n (value) => value === undefined,\n );\n }\n\n return true;\n }\n\n /**\n *\n * Input events methods\n *\n */\n private onChangeHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onValidate?.(this.getValidityData(event));\n }\n\n private onFocusHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onBlurHandler(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event));\n }\n\n private onInputSubmitRequest(\n formOptions: HostedFormOptions,\n event: PayPalCommerceCardFieldsState,\n ): void {\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event));\n }\n\n /**\n *\n * PayPal Commerce Accelerated checkout related methods\n *\n */\n // TODO: remove this part when PPCP AXO A/B testing will be finished\n private shouldInitializePayPalFastlane(methodId: string) {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalCommercePaymentProviderCustomer = isPayPalCommerceAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return (\n paymentMethod?.initializationData?.isAcceleratedCheckoutEnabled &&\n paymentMethod?.initializationData?.isPayPalCommerceAnalyticsV2Enabled &&\n !paypalCommercePaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when PPCP AXO A/B testing will be finished\n private async initializePayPalFastlaneOrThrow(methodId: string): Promise {\n try {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n if (!initializationData?.connectClientToken) {\n return;\n }\n\n const payPalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n payPalFastlaneSdk,\n !!initializationData?.isDeveloperModeApplicable,\n );\n } catch (_: unknown) {\n // We should avoid throwing any error from this flow to do no brake default flow\n // This flow is optional\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\n]);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n BirthDate,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport {\n PaypalCommerceRatePay,\n WithPayPalCommerceRatePayPaymentInitializeOptions,\n} from './paypal-commerce-ratepay-initialize-options';\n\nconst POLLING_INTERVAL = 3000;\nconst MAX_POLLING_TIME = 300000;\n\nexport default class PaypalCommerceRatepayPaymentStrategy implements PaymentStrategy {\n private guid?: string;\n private paypalcommerceratepay?: PaypalCommerceRatePay;\n private loadingIndicatorContainer?: string;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private pollingInterval: number = POLLING_INTERVAL,\n private maxPollingIntervalTime: number = MAX_POLLING_TIME,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceRatePayPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, paypalcommerceratepay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerceratepay) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerceratepay\" argument is not provided.`,\n );\n }\n\n const { legalTextContainer, container, loadingContainerId } = paypalcommerceratepay;\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.container\" argument is not provided.`,\n );\n }\n\n if (!legalTextContainer) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.legalTextContainer\" argument is not provided.`,\n );\n }\n\n if (!loadingContainerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.loadingContainerId\" argument is not provided.`,\n );\n }\n\n this.loadingIndicatorContainer = loadingContainerId;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { merchantId } = paymentMethod.initializationData || {};\n\n if (!merchantId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because merchantId argument is not provided.`,\n );\n }\n\n this.paypalcommerceratepay = paypalcommerceratepay;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.createFraudNetScript(merchantId, methodId, gatewayId);\n\n this.loadFraudnetConfig();\n\n this.renderLegalText(legalTextContainer, container);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n const { getFieldsValues } = this.paypalcommerceratepay || {};\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!getFieldsValues || typeof getFieldsValues !== 'function') {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.getFieldsValues\" argument is not provided.`,\n );\n }\n\n this.toggleLoadingIndicator(true);\n\n try {\n const orderId = await this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n { metadataId: this.guid },\n );\n\n const { ratepayBirthDate, ratepayPhoneNumber, ratepayPhoneCountryCode } =\n getFieldsValues();\n\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: payment.methodId,\n rate_pay: {\n birth_date: this.normalizeDate(ratepayBirthDate),\n phone: {\n national_number: ratepayPhoneNumber,\n country_code: ratepayPhoneCountryCode.split('+')[1],\n },\n },\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n\n return await new Promise((resolve, reject) => {\n this.initializePollingMechanism(\n payment.methodId,\n resolve,\n reject,\n payment.gatewayId,\n );\n });\n } catch (error: unknown) {\n this.handleError(error);\n\n return new Promise((_resolve, reject) => reject());\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n const { legalTextContainer } = this.paypalcommerceratepay || {};\n const fraudNetScript = document.querySelectorAll('[data-id=\"fraudnetScript\"]')[0];\n const fraudNetConfig = document.querySelectorAll('[data-id=\"fraudnetConfig\"]')[0];\n\n this.deinitializePollingMechanism();\n\n fraudNetScript.remove();\n fraudNetConfig.remove();\n\n if (legalTextContainer) {\n const legalTextContainerElement = document.getElementById(legalTextContainer);\n\n legalTextContainerElement?.remove();\n }\n\n return Promise.resolve();\n }\n\n private normalizeDate(date: BirthDate) {\n const formattedDate = this.formatDate(date.getDate());\n const formattedMonth = this.formatDate(date.getMonth() + 1);\n\n return `${date.getFullYear()}-${formattedMonth}-${formattedDate}`;\n }\n\n private formatDate(date: number): string {\n return `${date < 10 ? 0 : ''}${date}`;\n }\n\n private renderLegalText(legalTextContainerElementId: string, container: string) {\n const legalTextContainerId = legalTextContainerElementId;\n const buttonContainerId = container.split('#')[1];\n const buttonContainer = document.getElementById(buttonContainerId);\n const buttonContainerParent = buttonContainer?.parentNode;\n const legalTextContainer = document.createElement('div');\n\n legalTextContainer.style.marginBottom = '20px';\n legalTextContainer.setAttribute('id', legalTextContainerId);\n buttonContainerParent?.prepend(legalTextContainer);\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const ratePayButton = paypalSdk.Legal({\n fundingSource: paypalSdk.Legal.FUNDING.PAY_UPON_INVOICE,\n });\n const legalTextContainerElement = document.getElementById(legalTextContainerId);\n\n if (legalTextContainerElement) {\n ratePayButton.render(`#${legalTextContainerId}`);\n } else {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"legalTextContainerElement\" argument is not found.`,\n );\n }\n }\n\n private handleError(error: unknown): void {\n const { onError } = this.paypalcommerceratepay || {};\n\n this.resetPollingMechanism();\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n private createFraudNetScript(merchantId: string, methodId: string, gatewayId: string) {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n const { testMode } = paymentMethod.config;\n const scriptElement = document.createElement('script');\n\n scriptElement.setAttribute('type', 'application/json');\n scriptElement.setAttribute('fncls', 'fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99');\n scriptElement.setAttribute('data-id', 'fraudnetScript');\n this.guid = this.generateGUID();\n\n const fraudNetConfig = {\n f: this.guid,\n s: `${merchantId}_checkout-page`,\n sandbox: testMode,\n };\n\n scriptElement.innerHTML = JSON.stringify(fraudNetConfig);\n document.body.appendChild(scriptElement);\n }\n\n private generateGUID() {\n let guid = '';\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n for (let i = 0; i < 32; i += 1) {\n const randomIndex = Math.floor(Math.random() * characters.length);\n\n guid += characters[randomIndex];\n }\n\n return guid;\n }\n\n private loadFraudnetConfig() {\n const script = document.createElement('script');\n\n script.setAttribute('data-id', 'fraudnetConfig');\n script.src = 'https://c.paypal.com/da/r/fb.js';\n document.body.appendChild(script);\n }\n\n private async reinitializeStrategy(\n options: PaymentInitializeOptions & WithPayPalCommerceRatePayPaymentInitializeOptions,\n ): Promise {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n resolvePromise: () => void,\n rejectPromise: () => void,\n gatewayId?: string,\n ): Promise {\n await new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, this.pollingInterval);\n\n this.stopPolling = () => {\n clearTimeout(timeout);\n this.toggleLoadingIndicator(false);\n\n return reject();\n };\n });\n\n try {\n this.pollingTimer += this.pollingInterval;\n\n const orderStatus = await this.paypalCommerceIntegrationService.getOrderStatus(\n 'paypalcommercealternativemethods',\n {\n params: {\n useMetadata: true,\n },\n },\n );\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.PollingStop;\n const isPollingError = orderStatus === PayPalOrderStatus.PollingError;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return resolvePromise();\n }\n\n if (isPollingError) {\n return rejectPromise();\n }\n\n if (!isOrderApproved && this.pollingTimer < this.maxPollingIntervalTime) {\n return await this.initializePollingMechanism(\n methodId,\n resolvePromise,\n rejectPromise,\n gatewayId,\n );\n }\n\n await this.reinitializeStrategy({\n methodId,\n gatewayId,\n paypalcommerceratepay: this.paypalcommerceratepay,\n });\n\n this.handleError(new TimeoutError());\n } catch (error) {\n this.handleError(error);\n rejectPromise();\n }\n }\n\n private deinitializePollingMechanism(): void {\n this.stopPolling();\n this.pollingTimer = 0;\n }\n\n private resetPollingMechanism(): void {\n this.deinitializePollingMechanism();\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\nimport { LOADING_INDICATOR_STYLES } from '../paypal-commerce-constants';\n\nimport PaypalCommerceRatepayPaymentStrategy from './paypal-commerce-ratepay-payment-strategy';\n\nconst createPaypalCommerceRatepayPaymentStrategy: PaymentStrategyFactory<\n PaypalCommerceRatepayPaymentStrategy\n> = (paymentIntegrationService) =>\n new PaypalCommerceRatepayPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({\n containerStyles: { ...LOADING_INDICATOR_STYLES, position: 'fixed' },\n }),\n );\n\nexport default toResolvableModule(createPaypalCommerceRatepayPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods', id: 'ratepay' },\n]);\n","import {\n PaymentProviderCustomer,\n PayPalConnectCustomer,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n// TODO: update PayPalConnectCustomer with PayPalFastlaneCustomer\nexport default function isPayPalFastlaneCustomer(\n customer?: PaymentProviderCustomer,\n): customer is PayPalConnectCustomer {\n if (!customer) {\n return false;\n }\n\n return (\n 'authenticationState' in customer || 'addresses' in customer || 'instruments' in customer\n );\n}\n","import {\n CardInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalFastlaneCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneCardComponentMethods,\n PayPalFastlaneCardComponentOptions,\n PayPalFastlanePaymentFormattedPayload,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\n\nimport { WithPayPalCommerceFastlanePaymentInitializeOptions } from './paypal-commerce-fastlane-payment-initialize-options';\n\nexport default class PaypalCommerceFastlanePaymentStrategy implements PaymentStrategy {\n private paypalComponentMethods?: PayPalFastlaneCardComponentMethods;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceSdk: PayPalCommerceSdk,\n private paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n /**\n *\n * Default methods\n *\n * */\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceFastlanePaymentInitializeOptions,\n ): Promise {\n // TODO: remove paypalcommerceacceleratedcheckout if it was removed on checkout js side\n const { methodId, paypalcommercefastlane } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercefastlane) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane\" argument is not provided.',\n );\n }\n\n if (!paypalcommercefastlane.onInit || typeof paypalcommercefastlane.onInit !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane.onInit\" argument is not provided or it is not a function.',\n );\n }\n\n if (\n !paypalcommercefastlane.onChange ||\n typeof paypalcommercefastlane.onChange !== 'function'\n ) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercefastlane.onChange\" argument is not provided or it is not a function.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod.initializationData || {};\n\n const paypalFastlaneSdk = await this.paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n const paypalFastlaneStyling = isFastlaneStylingEnabled\n ? paymentMethod?.initializationData?.fastlaneStyles\n : {};\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStyling,\n paypalcommercefastlane?.styles,\n );\n\n await this.paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n !!isDeveloperModeApplicable,\n fastlaneStyles,\n );\n\n if (this.shouldRunAuthenticationFlow()) {\n await this.runPayPalAuthenticationFlowOrThrow(methodId);\n }\n\n await this.initializePayPalPaymentComponent();\n\n paypalcommercefastlane.onInit((container: string) =>\n this.renderPayPalPaymentComponent(container),\n );\n paypalcommercefastlane.onChange(() => this.handlePayPalStoredInstrumentChange(methodId));\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData, methodId } = payment;\n\n const isVaultedFlow = paymentData && isVaultedInstrument(paymentData);\n\n try {\n const paymentPayload = isVaultedFlow\n ? await this.prepareVaultedInstrumentPaymentPayload(methodId, paymentData)\n : await this.preparePaymentPayload(methodId, paymentData);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(\n paymentPayload,\n );\n\n // TODO: we should probably update this method with removeStorageSessionId for better reading experience\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(true);\n } catch (error) {\n if (error instanceof Error && error.name !== 'FastlaneError') {\n throw error;\n }\n\n return Promise.reject();\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n return Promise.resolve();\n }\n\n /**\n *\n * Authentication flow methods\n *\n */\n private shouldRunAuthenticationFlow(): boolean {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomerOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const paypalFastlaneSessionId = this.paypalCommerceFastlaneUtils.getStorageSessionId();\n\n if (\n !customer.isGuest ||\n paypalFastlaneCustomer?.authenticationState ===\n PayPalFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return !paypalFastlaneCustomer?.authenticationState && paypalFastlaneSessionId === cart.id;\n }\n\n private async runPayPalAuthenticationFlowOrThrow(methodId: string): Promise {\n try {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const customerEmail = customer?.email || billingAddress?.email || '';\n\n const { customerContextId } =\n await this.paypalCommerceFastlaneUtils.lookupCustomerOrThrow(customerEmail);\n\n const authenticationResult =\n await this.paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, instruments } =\n this.paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n });\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState ===\n PayPalFastlaneAuthenticationState.CANCELED;\n\n this.paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cart.id,\n );\n } catch (error) {\n // Info: Do not throw anything here to avoid blocking customer from passing checkout flow\n }\n }\n\n /**\n *\n * PayPal Fastlane Card Component rendering method\n *\n */\n private async initializePayPalPaymentComponent(): Promise {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n const phone = billingAddress.phone;\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`.trim();\n\n const paypalFastlane = this.paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const cardComponentOptions: PayPalFastlaneCardComponentOptions = {\n fields: {\n cardholderName: {\n prefill: fullName,\n enabled: true,\n },\n ...(phone && {\n phoneNumber: {\n prefill: phone,\n },\n }),\n },\n };\n\n this.paypalComponentMethods = await paypalFastlane.FastlaneCardComponent(\n cardComponentOptions,\n );\n }\n\n private renderPayPalPaymentComponent(container?: string): void {\n const paypalComponentMethods = this.getPayPalComponentMethodsOrThrow();\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render card component because \"container\" argument is not provided.',\n );\n }\n\n paypalComponentMethods.render(container);\n }\n\n private getPayPalComponentMethodsOrThrow(): PayPalFastlaneCardComponentMethods {\n if (!this.paypalComponentMethods) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalComponentMethods;\n }\n\n /**\n *\n * Payment Payload preparation methods\n *\n */\n private async prepareVaultedInstrumentPaymentPayload(\n methodId: string,\n paymentData: VaultedInstrument,\n ): Promise> {\n const { instrumentId } = paymentData;\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(methodId, {\n cartId,\n });\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: orderId,\n token: instrumentId,\n },\n },\n },\n };\n }\n\n private async preparePaymentPayload(\n methodId: string,\n paymentData: OrderPaymentRequestBody['paymentData'],\n ): Promise> {\n const state = this.paymentIntegrationService.getState();\n const cartId = state.getCartOrThrow().id;\n const billingAddress = state.getBillingAddressOrThrow();\n\n const fullName = `${billingAddress.firstName} ${billingAddress.lastName}`.trim();\n\n const { getPaymentToken } = this.getPayPalComponentMethodsOrThrow();\n\n const { id } = await getPaymentToken({\n name: { fullName },\n billingAddress: this.paypalCommerceFastlaneUtils.mapBcToPayPalAddress(billingAddress),\n });\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(methodId, {\n cartId,\n });\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n formattedPayload: {\n paypal_fastlane_token: {\n order_id: orderId,\n token: id,\n },\n },\n },\n };\n }\n\n /**\n *\n * PayPal Fastlane instrument change\n *\n */\n private async handlePayPalStoredInstrumentChange(\n methodId: string,\n ): Promise {\n const paypalAxoSdk = this.paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const { selectionChanged, selectedCard } = await paypalAxoSdk.profile.showCardSelector();\n\n if (selectionChanged) {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const selectedInstrument = this.paypalCommerceFastlaneUtils.mapPayPalToBcInstrument(\n methodId,\n selectedCard,\n )[0];\n\n await this.paymentIntegrationService.updatePaymentProviderCustomer({\n ...paypalFastlaneCustomer,\n instruments: [selectedInstrument],\n });\n\n return selectedInstrument;\n }\n\n return undefined;\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceRequestSender from '../paypal-commerce-request-sender';\n\nimport PayPalCommerceFastlanePaymentStrategy from './paypal-commerce-fastlane-payment-strategy';\n\nconst createPayPalCommerceFastlanePaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceFastlanePaymentStrategy\n> = (paymentIntegrationService) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceFastlanePaymentStrategy(\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n );\n};\n\nexport default toResolvableModule(createPayPalCommerceFastlanePaymentStrategy, [\n { id: 'paypalcommerceacceleratedcheckout' }, // PayPal Fastlane relates to 'paypalcommerceacceleratedcheckout' method id\n]);\n","import { CardinalThreeDSecureFlow } from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n OrderRequestBody,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class PaypalProPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n protected paymentIntegrationService: PaymentIntegrationService,\n private threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(paymentIntegrationService);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this.threeDSecureFlow.prepare(paymentMethod);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n\n const state = this.paymentIntegrationService.getState();\n\n if (state.getPaymentStatus() === PaymentStatusTypes.ACKNOWLEDGE) {\n await this.paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: { methodId },\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n if (state.getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this.threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n} from '@bigcommerce/checkout-sdk/cardinal-integration';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PaypalProPaymentStrategy from './paypal-pro-payment-strategy';\n\nconst createPayPalProPaymentStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PaypalProPaymentStrategy(\n paymentIntegrationService,\n new CardinalThreeDSecureFlow(\n paymentIntegrationService,\n new CardinalClient(new CardinalScriptLoader(getScriptLoader())),\n ),\n );\n\nexport default toResolvableModule(createPayPalProPaymentStrategy, [{ id: 'paypal' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n getBrowserInfo,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class SagePayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private _formPoster: FormPoster,\n ) {\n super(paymentIntegrationService);\n }\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData } = payment;\n\n if (!paymentData) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n if (this._isThreeDSTwoExperimentOn()) {\n const newPaymentData = {\n ...paymentData,\n browser_info: getBrowserInfo(),\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error: Error) => {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n let payload;\n\n if (this._isThreeDSTwoExperimentOn() && !error.body.three_ds_result.merchant_data) {\n payload = {\n creq: error.body.three_ds_result.payer_auth_request,\n };\n } else {\n payload = {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n };\n }\n\n this._formPoster.postForm(\n error.body.three_ds_result.acs_url,\n payload,\n undefined,\n '_top',\n );\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const order = state.getOrder();\n\n if (order && state.getPaymentStatus() === PaymentStatusTypes.FINALIZE) {\n this.paymentIntegrationService.finalizeOrder(options);\n }\n\n return super.finalize();\n }\n\n private _isThreeDSTwoExperimentOn(): boolean {\n return (\n this.paymentIntegrationService.getState().getStoreConfigOrThrow().checkoutSettings\n .features['INT-4994.Opayo_3DS2'] === true\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SagePayPaymentStrategy from './sage-pay-payment-strategy';\n\nconst createSagePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new SagePayPaymentStrategy(paymentIntegrationService, createFormPoster());\n};\n\nexport default toResolvableModule(createSagePayPaymentStrategy, [{ id: 'sagepay' }]);\n","import { ExternalPaymentStrategy } from '@bigcommerce/checkout-sdk/external-integration';\n\nexport default class SezzlePaymentStrategy extends ExternalPaymentStrategy {\n protected redirectUrl(url: string): void {\n window.location.replace(url);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SezzlePaymentStrategy from './sezzle-payment-strategy';\n\nconst createSezzlePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new SezzlePaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createSezzlePaymentStrategy, [{ id: 'sezzle' }]);\n","export enum SquareIntent {\n CHARGE = 'CHARGE',\n STORE = 'STORE',\n}\n","import { fromEvent, merge, Subscription } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\n\nimport {\n BillingAddress,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentExecuteError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SquareIntent } from './enums';\nimport SquareV2PaymentInitializeOptions from './squarev2-payment-initialize-options';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\nimport {\n BillingContact,\n Card,\n CardInputEvent,\n CardInputEventTypes,\n ChargeVerifyBuyerDetails,\n Payments,\n SqEvent,\n StoreVerifyBuyerDetails,\n} from './types';\n\nexport interface SquareV2PaymentProcessorOptions {\n applicationId: string;\n locationId?: string;\n testMode?: boolean;\n}\n\nexport default class SquareV2PaymentProcessor {\n private _payments?: Payments;\n private _card?: Card;\n private _formValidationSubscription?: Subscription;\n\n constructor(\n private _scriptLoader: SquareV2ScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize({\n testMode,\n applicationId,\n locationId,\n }: SquareV2PaymentProcessorOptions): Promise {\n const square = await this._scriptLoader.load(testMode);\n\n this._payments = square.payments(applicationId, locationId);\n }\n\n async deinitialize(): Promise {\n if (this._formValidationSubscription) {\n this._formValidationSubscription.unsubscribe();\n }\n\n if (this._card) {\n await this._card.destroy();\n }\n\n this._formValidationSubscription = undefined;\n this._card = undefined;\n this._payments = undefined;\n }\n\n async initializeCard({\n containerId,\n style,\n onValidationChange,\n }: SquareV2PaymentInitializeOptions): Promise {\n const { postalCode } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n this._card = await this._getPayments().card();\n await this._card.attach(`#${containerId}`);\n\n try {\n await this._card.configure({ postalCode, style });\n } catch (_error) {\n /* Do nothing: we should not block shoppers from buying. */\n }\n\n if (onValidationChange) {\n this._formValidationSubscription = this._subscribeToFormValidation(\n this._card,\n onValidationChange,\n );\n }\n }\n\n async tokenize(): Promise {\n const result = await this._getCard().tokenize();\n\n if (result.status !== 'OK' || !result.token) {\n let errorMessage = `Tokenization failed with status: ${result.status}`;\n\n if (result.errors) {\n errorMessage += ` and errors: ${JSON.stringify(result.errors)}`;\n }\n\n throw new PaymentExecuteError(\n 'payment.errors.card_error',\n 'SquareV2TokenizationError',\n errorMessage,\n );\n }\n\n return result.token;\n }\n\n async verifyBuyer(token: string, intent: SquareIntent): Promise {\n return intent === SquareIntent.CHARGE\n ? this._chargeVerifyBuyer(token)\n : this._storeVerifyBuyer(token);\n }\n\n private _getPayments(): Payments {\n return guard(\n this._payments,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _subscribeToFormValidation(\n card: Card,\n observer: Required['onValidationChange'],\n ): Subscription {\n const blacklist = ['cardNumber', 'cvv'];\n const invalidFields = new Set(blacklist);\n const eventObservables = [\n 'focusClassAdded',\n 'focusClassRemoved',\n 'errorClassAdded',\n 'errorClassRemoved',\n 'cardBrandChanged',\n 'postalCodeChanged',\n ].map((eventType) => fromEvent(card, eventType as CardInputEventTypes));\n\n return merge(...eventObservables)\n .pipe(\n map((event: SqEvent): boolean => {\n const {\n detail: {\n field,\n currentState: { isCompletelyValid },\n },\n } = event;\n\n if (blacklist.includes(field)) {\n invalidFields[isCompletelyValid ? 'delete' : 'add'](field);\n }\n\n return invalidFields.size === 0;\n }),\n distinctUntilChanged(),\n )\n .subscribe(observer);\n }\n\n private _getCard(): Card {\n return guard(\n this._card,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _mapToSquareBillingContact({\n firstName: givenName,\n lastName: familyName,\n address1,\n address2,\n city,\n stateOrProvinceCode: state,\n postalCode,\n countryCode,\n email,\n phone,\n }: BillingAddress): BillingContact {\n return {\n givenName,\n familyName,\n addressLines: [address1, address2],\n city,\n state,\n postalCode,\n countryCode,\n email,\n phone,\n };\n }\n\n private async _chargeVerifyBuyer(token: string): Promise {\n const { getCheckoutOrThrow, getBillingAddressOrThrow } =\n this._paymentIntegrationService.getState();\n const { outstandingBalance, cart } = getCheckoutOrThrow();\n\n const details: ChargeVerifyBuyerDetails = {\n amount: outstandingBalance.toString(),\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n currencyCode: cart.currency.code,\n intent: SquareIntent.CHARGE,\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n\n private async _storeVerifyBuyer(token: string): Promise {\n const { getBillingAddressOrThrow } = this._paymentIntegrationService.getState();\n\n const details: StoreVerifyBuyerDetails = {\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n intent: SquareIntent.STORE,\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n}\n","import {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SquareIntent } from './enums';\nimport { WithSquareV2PaymentInitializeOptions } from './squarev2-payment-initialize-options';\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport {\n SquareCreditCardTokens,\n SquareFormattedVaultedInstrument,\n SquareInitializationData,\n SquarePaymentMethodInitializationData,\n} from './types';\n\nexport default class SquareV2PaymentStrategy implements PaymentStrategy {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _squareV2PaymentProcessor: SquareV2PaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithSquareV2PaymentInitializeOptions,\n ): Promise {\n if (!options?.squarev2?.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const { methodId, squarev2 } = options;\n const {\n config: { testMode },\n initializationData,\n } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n const { applicationId, locationId } = initializationData || {};\n\n if (!applicationId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this._squareV2PaymentProcessor.initialize({\n applicationId,\n locationId,\n testMode,\n });\n await this._squareV2PaymentProcessor.initializeCard(squarev2);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, paymentData } = payment;\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n await this._paymentIntegrationService.submitOrder();\n\n const submitPaymentPayload =\n paymentData && isVaultedInstrument(paymentData)\n ? await this._getVaultedInstrumentPayload(methodId, paymentData)\n : await this._getCardPayload(shouldSaveInstrument);\n\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n ...submitPaymentPayload,\n vault_payment_instrument: shouldSaveInstrument || false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || false,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._squareV2PaymentProcessor.deinitialize();\n }\n\n private _shouldVerify(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return features['PROJECT-3828.add_3ds_support_on_squarev2'];\n }\n\n private async _getCardPayload(shouldSaveInstrument?: boolean) {\n const cardTokenizationResult = await this._squareV2PaymentProcessor.tokenize();\n\n if (!this._shouldVerify()) {\n return {\n credit_card_token: {\n token: cardTokenizationResult,\n },\n };\n }\n\n let tokenData: SquareCreditCardTokens = {\n nonce: cardTokenizationResult,\n token: await this._squareV2PaymentProcessor.verifyBuyer(\n cardTokenizationResult,\n SquareIntent.CHARGE,\n ),\n };\n\n if (shouldSaveInstrument) {\n // INFO: additional 'tokenize' is required to verify and save the card\n // for each 'verifyBuyer' we need to generate new token\n const tokenForSavingCard = await this._squareV2PaymentProcessor.tokenize();\n\n tokenData = {\n ...tokenData,\n store_card_nonce: tokenForSavingCard,\n store_card_token: await this._squareV2PaymentProcessor.verifyBuyer(\n tokenForSavingCard,\n SquareIntent.STORE,\n ),\n };\n }\n\n return {\n credit_card_token: {\n token: JSON.stringify(tokenData),\n },\n };\n }\n\n private async _getVaultedInstrumentPayload(\n methodId: string,\n paymentData: VaultedInstrument,\n ): Promise {\n const { instrumentId } = paymentData;\n const verificationToken = this._shouldVerify()\n ? await this._squareV2PaymentProcessor.verifyBuyer(\n await this._getSquareCardIdOrThrow(methodId, instrumentId),\n SquareIntent.CHARGE,\n )\n : undefined;\n\n return {\n bigpay_token: {\n token: instrumentId,\n ...(verificationToken && { three_d_secure: { token: verificationToken } }),\n },\n };\n }\n\n private async _getSquareCardIdOrThrow(methodId: string, instrumentId: string): Promise {\n const state = await this._paymentIntegrationService.loadPaymentMethod(methodId, {\n params: { method: methodId, bigpayToken: instrumentId },\n });\n\n const { initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { cardId } = initializationData || {};\n\n if (!cardId) {\n throw new PaymentArgumentInvalidError(['cardId']);\n }\n\n return cardId;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport assertSquareV2Window from './is-squarev2-window';\nimport { Square } from './types';\n\nexport enum SquareV2WebPaymentsSdkEnv {\n LIVE = 'https://web.squarecdn.com/v1/square.js',\n SANDBOX = 'https://sandbox.web.squarecdn.com/v1/square.js',\n}\n\nexport default class SquareV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? SquareV2WebPaymentsSdkEnv.SANDBOX : SquareV2WebPaymentsSdkEnv.LIVE,\n );\n\n assertSquareV2Window(window);\n\n return window.Square;\n }\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport type { Square } from './types';\n\ninterface SquareV2HostWindow extends Window {\n Square: Square;\n}\n\nfunction isSquareV2Window(window: Window): window is SquareV2HostWindow {\n return 'Square' in window;\n}\n\nexport default function assertSquareV2Window(window: Window): asserts window is SquareV2HostWindow {\n if (!isSquareV2Window(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport SquareV2PaymentStrategy from './squarev2-payment-strategy';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\n\nconst createSquareV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new SquareV2PaymentStrategy(\n paymentIntegrationService,\n new SquareV2PaymentProcessor(\n new SquareV2ScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n ),\n );\n};\n\nexport default toResolvableModule(createSquareV2PaymentStrategy, [{ id: 'squarev2' }]);\n","import { IndividualCardElementOptions } from './stripev3';\n\nexport default function isIndividualCardElementOptions(\n individualCardElementOptions: any,\n): individualCardElementOptions is IndividualCardElementOptions {\n return (\n individualCardElementOptions !== null &&\n typeof individualCardElementOptions === 'object' &&\n 'cardNumberElementOptions' in individualCardElementOptions &&\n 'cardCvcElementOptions' in individualCardElementOptions &&\n 'cardExpiryElementOptions' in individualCardElementOptions &&\n typeof individualCardElementOptions.cardNumberElementOptions !== 'undefined' &&\n typeof individualCardElementOptions.cardCvcElementOptions !== 'undefined' &&\n typeof individualCardElementOptions.cardExpiryElementOptions !== 'undefined'\n );\n}\n","interface BaseElementOptions {\n /**\n * Customize the appearance of an element using CSS properties passed in a [Style](https://stripe.com/docs/js/appendix/style) object,\n * which consists of CSS properties nested under objects for each variant.\n */\n style?: StripeElementStyle;\n\n /**\n * Set custom class names on the container DOM element when the Stripe element is in a particular state.\n */\n classes?: StripeElementClasses;\n\n /**\n * Applies a disabled state to the Element such that user input is not accepted. Default is false.\n */\n disabled?: boolean;\n}\n\nexport interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {\n card?: StripeElement;\n}\n\nexport interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {\n ideal?: StripeElement;\n}\n\nexport interface CreatePaymentMethodSepaData extends PaymentMethodCreateParams {\n sepa_debit?: StripeElement;\n}\n\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * Status of this PaymentIntent. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses).\n */\n status: 'succeeded' | string;\n\n /**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\n last_payment_error: LastPaymentError | null;\n}\n\n/**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\nexport interface LastPaymentError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n}\n\n/**\n * The PaymentMethod object\n */\nexport interface PaymentMethod {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value.\n * It contains additional information specific to the PaymentMethod type.\n */\n type: string;\n}\n\nexport interface PaymentMethodCreateParams {\n /**\n * Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.\n */\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n\n /**\n * A human-readable code for the error obtained\n */\n code?: string;\n}\n\n/**\n * CSS properties supported by Stripe.js.\n */\ninterface StripeElementCSSProperties {\n /**\n * The [background-color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) CSS property.\n *\n * This property works best with the `::selection` pseudo-class.\n * In other cases, consider setting the background color on the element's container instaed.\n */\n backgroundColor?: string;\n\n /**\n * The [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS property.\n */\n color?: string;\n\n /**\n * The [font-family](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) CSS property.\n */\n fontFamily?: string;\n\n /**\n * The [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) CSS property.\n */\n fontSize?: string;\n\n /**\n * The [font-smoothing](https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing) CSS property.\n */\n fontSmoothing?: string;\n\n /**\n * The [font-style](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) CSS property.\n */\n fontStyle?: string;\n\n /**\n * The [font-variant](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) CSS property.\n */\n fontVariant?: string;\n\n /**\n * The [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) CSS property.\n */\n fontWeight?: string;\n\n /**\n * A custom property, used to set the color of the icons that are rendered in an element.\n */\n iconColor?: string;\n\n /**\n * The [line-height](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property.\n *\n * To avoid cursors being rendered inconsistently across browsers, consider using a padding on the element's container instead.\n */\n lineHeight?: string;\n\n /**\n * The [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) CSS property.\n */\n letterSpacing?: string;\n\n /**\n * The [text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) CSS property.\n *\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n textAlign?: string;\n\n /**\n * The [padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) CSS property.\n *\n * Available for the `idealBank` element.\n * Accepts integer `px` values.\n */\n padding?: string;\n\n /**\n * The [text-decoration](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) CSS property.\n */\n textDecoration?: string;\n\n /**\n * The [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) CSS property.\n */\n textShadow?: string;\n\n /**\n * The [text-transform](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) CSS property.\n */\n textTransform?: string;\n}\n\ninterface StripeElementStyleVariant extends StripeElementCSSProperties {\n ':hover'?: StripeElementCSSProperties;\n\n ':focus'?: StripeElementCSSProperties;\n\n '::placeholder'?: StripeElementCSSProperties;\n\n '::selection'?: StripeElementCSSProperties;\n\n ':-webkit-autofill'?: StripeElementCSSProperties;\n\n /**\n * Available for all elements except the `paymentRequestButton` element\n */\n ':disabled'?: StripeElementCSSProperties;\n\n /**\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n '::-ms-clear'?: StripeElementCSSProperties & { display: string };\n}\n\nexport interface CardElementOptions extends BaseElementOptions {\n /**\n * A pre-filled set of values to include in the input (e.g., {postalCode: '94110'}).\n * Note that sensitive card information (card number, CVC, and expiration date)\n * cannot be pre-filled\n */\n value?: string;\n\n /**\n * Hide the postal code field. Default is false. If you are already collecting a\n * full billing address or postal code elsewhere, set this to true.\n */\n hidePostalCode?: boolean;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n\n /*\n * Hides the icon in the Element, Default is false\n */\n hideIcon?: boolean;\n}\n\ninterface BaseIndividualElementOptions extends BaseElementOptions {\n containerId: string;\n}\n\nexport interface CardNumberElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n\n showIcon?: boolean;\n /**\n * Appearance of the icon in the Element. Either `solid` or `default`\n */\n iconStyle?: IconStyle;\n}\n\nexport interface CardExpiryElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface CardCvcElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface IbanElementOptions extends BaseElementOptions {\n /**\n * Specify the list of countries or country-groups whose IBANs you want to allow.\n * Must be ['SEPA'].\n */\n supportedCountries?: string[];\n\n /**\n * Customize the country and format of the placeholder IBAN. Default is DE.\n */\n placeholderCountry?: string;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n}\n\nexport interface IdealElementOptions extends BaseElementOptions {\n value?: string;\n\n /**\n * Hides the icon in the Element. Default is false.\n */\n hideIcon?: boolean;\n}\n\nexport interface ZipCodeElementOptions {\n containerId: string;\n}\n\nexport enum IconStyle {\n Solid = 'solid',\n Default = 'default',\n}\n\nexport interface StripeElementStyle {\n /**\n * Base variant—all other variants inherit from these styles.\n */\n base?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has valid input.\n */\n complete?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has no customer input.\n */\n empty?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has invalid input.\n */\n invalid?: StripeElementStyleVariant;\n}\n\nexport interface StripeElementClasses {\n /**\n * The base class applied to the container. Defaults to StripeElement.\n */\n base?: string;\n\n /**\n * The class name to apply when the Element is complete. Defaults to StripeElement--complete.\n */\n complete?: string;\n\n /**\n * The class name to apply when the Element is empty. Defaults to StripeElement--empty.\n */\n empty?: string;\n\n /**\n * The class name to apply when the Element is focused. Defaults to StripeElement--focus.\n */\n focus?: string;\n\n /**\n * The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.\n */\n invalid?: string;\n\n /**\n * The class name to apply when the Element has its value autofilled by the browser\n * (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.\n */\n webkitAutoFill?: string;\n}\n\nexport interface StripeAddress {\n /**\n * City, district, suburb, town, or village.\n */\n city?: string;\n\n /**\n * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).\n */\n country?: string;\n\n /**\n * Address line 1 (e.g., street, PO Box, or company name).\n */\n line1: string;\n\n /**\n * Address line 2 (e.g., apartment, suite, unit, or building).\n */\n line2?: string;\n\n /**\n * ZIP or postal code.\n */\n postal_code?: string;\n\n /**\n * State, county, province, or region.\n */\n state?: string;\n}\n\nexport interface StripeBillingDetails {\n /**\n * Billing address.\n */\n address?: StripeAddress;\n\n /**\n * Email address.\n */\n email?: string;\n\n /**\n * Full name.\n */\n name?: string;\n\n /**\n * Billing phone number (including extension).\n */\n phone?: string;\n}\n\nexport interface StripeShippingAddress {\n /**\n * Shipping Address\n */\n address: StripeAddress;\n\n /**\n * Recipient name\n */\n name: string;\n\n /**\n * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.\n */\n carrier?: string;\n\n /**\n * Recipient phone (including extension).\n */\n phone?: string;\n\n /**\n * The tracking number for a physical product, obtained from the delivery service.\n * If multiple tracking numbers were generated for this purchase, please separate them with commas.\n */\n tracking_number?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmAlipayPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmAlipayPaymentData {\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmCardPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmCardPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodCardData;\n\n /*\n * The [shipping details](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping) for the payment, if collected.\n *\n * @recommended\n */\n shipping?: StripeShippingAddress;\n\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n\n /**\n * Indicates that you intend to make future payments with this PaymentIntent's payment method.\n *\n * If present, the payment method used with this PaymentIntent can be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer, even after the transaction completes.\n *\n * Use `on_session` if you intend to only reuse the payment method when your customer is present in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow.\n */\n setup_future_usage?: 'off_session' | 'on_session' | null;\n}\n\n/**\n * Data to be sent with a `stripe.confirmIdealPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmIdealPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodIdealData;\n\n /*\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmSEPAPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmSepaPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodSepaData;\n}\n\nexport type StripeConfirmPaymentData =\n | StripeConfirmAlipayPaymentData\n | StripeConfirmCardPaymentData\n | StripeConfirmIdealPaymentData\n | StripeConfirmSepaPaymentData\n | undefined;\n\nexport type StripeElementOptions =\n | CardElementOptions\n | CardExpiryElementOptions\n | CardNumberElementOptions\n | CardCvcElementOptions\n | IdealElementOptions\n | IbanElementOptions\n | ZipCodeElementOptions;\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n}\n\nexport interface StripeElements {\n /**\n * Creates a `AlipayElement` | `CardElement` | `CardCvcElement` |`CardExpiryElement` | `CardExpiryElement` | `CardNumberElement` | `IdealBankElement` | `IbanElement`.\n */\n create(elementType: StripeElementType, options?: StripeElementOptions): StripeElement;\n\n /**\n * Looks up a previously created `Element` by its type.\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CssFontSource {\n /**\n * A relative or absolute URL pointing to a CSS file with [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definitions, for example:\n * `https://fonts.googleapis.com/css?family=Open+Sans`\n * Note that if you are using a [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),\n * [additional directives](https://stripe.com/docs/security#content-security-policy) may be necessary.\n */\n cssSrc: string;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CustomFontSource {\n /**\n * The name to give the font.\n */\n family: string;\n\n /**\n * A valid [src](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src) value pointing to your\n * custom font file. This is usually (though not always) a link to a file with a .woff , .otf, or .svg suffix.\n */\n src: string;\n\n /**\n * A valid [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) value.\n */\n display?: string;\n\n /**\n * One of normal, italic, oblique. Defaults to normal.\n */\n style?: string;\n\n /**\n * A valid [unicode-range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) value.\n */\n unicodeRange?: string;\n\n /**\n * A valid [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight). Note that this is a string, not a number.\n */\n weight?: string;\n}\n\nexport type CustomFont = CssFontSource | CustomFontSource;\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n}\n\nexport interface StripeConfirmPaymentOptions {\n /**\n * Set this to false if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect). Default is true.\n */\n handleActions?: boolean;\n}\n\nexport interface StripeV3Client {\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options?: StripeElementsOptions): StripeElements;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment\n *\n * Use `stripe.confirmAlipayPayment` in the Alipay payment method creation flow when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with data you provide, and it will automatically\n * redirect the customer to the authorize the transaction. Once authorization is complete, the customer will be redirected\n * back to your specified `return_url`. When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmAlipayPayment` by default, will trigger a redirect when successful. If there is an error, or when handling\n * `next_actions` manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result` object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmAlipayPayment` may take several seconds to complete. During that time, you should disable your\n * form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result, you should\n * be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmAlipayPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmAlipayPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment\n *\n * Use `stripe.confirmCardPayment` when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents)\n * with `data` you provide and carry out 3DS or other next actions if they are required.\n *\n * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will\n * trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmCardPayment` will return a Promise which resolves with a result object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that stripe.confirmCardPayment may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n *\n * Additionally, `stripe.confirmCardPayment may trigger` a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication\n * challenge. This will be shown in a modal dialog and may be confusing for customers using assistive technologies like\n * screen readers. You should make your form accessible by ensuring that success or error messages are clearly read out\n * after this method completes.\n *\n */\n confirmCardPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmCardPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment\n *\n * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal)\n * flow when the customer submits your payment form. When called, it will confirm the `PaymentIntent` with `data` you\n * provide, and it will automatically redirect the customer to the authorize the transaction.\n * Once authorization is complete, the customer will be redirected back to your specified `return_url`.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * By default, `stripe.confirmIdealPayment` will trigger a redirect when successful. If there is an error, or when handling\n * next actions manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result`\n * object. This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmIdealPayment` may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmIdealPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmIdealPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n *\n * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit)\n * with Payment Methods flow when the customer submits your payment form. When called, it will confirm the\n * [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. Note that there are some additional\n * requirements to this flow that are not covered in this reference. Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit\n * for more details.\n *\n * When you confirm a PaymentIntent, it needs to have an attached PaymentMethod. In addition to confirming the PaymentIntent,\n * this method can automatically create and attach a new PaymentMethod for you. If you have already attached a\n * [PaymentMethod](https://stripe.com/docs/api/payment_methods) you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment\n */\n confirmSepaDebitPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\n data?: StripeConfirmSepaPaymentData,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /*\n * Use stripe.createPaymentMethod to convert payment information collected by elements into a PaymentMethod\n * object that you safely pass to your server to use in an API call.\n *\n * @docs https://stripe.com/docs/js/payment_methods/create_payment_method\n *\n * @param type: String, The type of the PaymentMethod to create. Refer to the PaymentMethod API for all possible values.\n * @param card: StripeElement, A card or cardNumber Element.\n * @param billing_details: StripeBillingDetails, Billing information associated with the PaymentMethod that\n * may be used or required by particular types of payment methods.\n */\n createPaymentMethod(\n params: CreatePaymentMethodParams,\n ): Promise<{ paymentMethod?: PaymentMethod; error?: StripeError }>;\n\n /*\n * Use stripe.handleCardAction in the Payment Intents API manual confirmation flow to handle a PaymentIntent\n * with the requires_action status. It will throw an error if the PaymentIntent has a different status.\n *\n * @docs https://stripe.com/docs/js/payment_intents/handle_card_action\n *\n * @param paymentIntentClientSecret: String, The client secret of the PaymentIntent to handle.\n */\n handleCardAction(\n paymentIntentClientSecret: string,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n}\n\nexport interface CreatePaymentMethodParams {\n type: StripePaymentMethodType;\n card: StripeElement;\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeHostWindow extends Window {\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeV3Client;\n}\n\nexport enum StripeElementType {\n Alipay = 'alipay',\n CardCvc = 'cardCvc',\n CardExpiry = 'cardExpiry',\n CardNumber = 'cardNumber',\n CreditCard = 'card',\n IDEAL = 'idealBank',\n Sepa = 'iban',\n}\n\nexport enum StripePaymentMethodType {\n Alipay = 'alipay',\n CreditCard = 'card',\n IDEAL = 'ideal',\n Sepa = 'sepa_debit',\n}\n\n/**\n * Initialization options.\n */\nexport interface StripeConfigurationOptions {\n /**\n * For usage with [Connect](https://stripe.com/docs/connect) only.\n * Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account.\n */\n stripeAccount: string;\n\n /**\n * Override your account's [API version](https://stripe.com/docs/api/versioning)\n */\n apiVersion?: string;\n\n /**\n * A locale used to globally configure localization in Stripe. Setting the locale here will localize error strings for all Stripe.js methods. It will also configure the locale for Elements and Checkout. Default is auto (Stripe detects the locale of the browser).\n * Note that Checkout supports a slightly different set of locales than Stripe.js.\n */\n locale?: string;\n\n betas?: string[];\n}\n\nexport interface StripeAdditionalActionData {\n redirect_url?: string;\n intent?: string;\n}\n\nexport interface StripeAdditionalAction {\n type: string;\n data: StripeAdditionalActionData;\n}\n\nexport interface StripeCardElements {\n [index: number]: StripeElement;\n}\n\nexport interface IndividualCardElementOptions {\n cardCvcElementOptions: CardCvcElementOptions;\n cardExpiryElementOptions: CardExpiryElementOptions;\n cardNumberElementOptions: CardNumberElementOptions;\n zipCodeElementOptions?: ZipCodeElementOptions;\n}\n\nexport interface StripeV3PaymentMethod extends PaymentMethod {\n initializationData: StripeV3InitializationData;\n}\n\nexport interface StripeV3InitializationData {\n stripePublishableKey: string;\n stripeConnectedAccount: string;\n useIndividualCardFields: boolean;\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport enum StripeV3ErrorType {\n AuthFailure = 'auth_failure',\n}\n\nexport default class StripeV3Error extends StandardError {\n subtype: string;\n\n constructor(subtype: StripeV3ErrorType) {\n super(getErrorMessage(subtype));\n\n this.type = 'stripev3_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: StripeV3ErrorType) {\n switch (type) {\n case StripeV3ErrorType.AuthFailure:\n return `User did not authenticate`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { includes, isEmpty, omitBy, some } from 'lodash';\n\nimport {\n Address,\n BillingAddress,\n Customer,\n HostedForm,\n HostedFormOptions,\n InvalidArgumentError,\n isBillingAddressLike,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StripeV3FormattedPayload,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isIndividualCardElementOptions from './is-individual-card-element-options';\nimport {\n PaymentIntent,\n StripeAdditionalAction,\n StripeAddress,\n StripeBillingDetails,\n StripeCardElements,\n StripeConfirmIdealPaymentData,\n StripeConfirmPaymentData,\n StripeConfirmSepaPaymentData,\n StripeElement,\n StripeElementOptions,\n StripeElements,\n StripeElementType,\n StripeError,\n PaymentMethod as StripePaymentMethod,\n StripePaymentMethodType,\n StripeV3Client,\n StripeV3PaymentMethod,\n} from './stripev3';\nimport StripeV3Error, { StripeV3ErrorType } from './stripev3-error';\nimport StripeV3PaymentInitializeOptions, {\n WithStripeV3PaymentInitializeOptions,\n} from './stripev3-initialize-options';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst APM_REDIRECT = [StripeElementType.Alipay, StripeElementType.IDEAL];\n\nexport default class StripeV3PaymentStrategy implements PaymentStrategy {\n private initializeOptions?: StripeV3PaymentInitializeOptions;\n private stripeV3Client?: StripeV3Client;\n private stripeElements?: StripeElements;\n private stripeElement?: StripeElement;\n private stripeCardElements?: StripeCardElements;\n private useIndividualCardFields?: boolean;\n private hostedForm?: HostedForm;\n private isDeinitialize?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeV3ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions & WithStripeV3PaymentInitializeOptions) {\n const { stripev3, methodId, gatewayId } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this.initializeOptions = stripev3;\n this.isDeinitialize = false;\n\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n const {\n initializationData: {\n stripePublishableKey,\n stripeConnectedAccount,\n useIndividualCardFields,\n },\n } = paymentMethod as StripeV3PaymentMethod;\n\n const form = this.getInitializeOptions().form;\n\n this.useIndividualCardFields = useIndividualCardFields;\n this.stripeV3Client = await this.loadStripeJs(stripePublishableKey, stripeConnectedAccount);\n\n if (\n this.isCreditCard(methodId) &&\n this.shouldShowTSVHostedForm(methodId, gatewayId) &&\n form\n ) {\n this.hostedForm = await this.mountCardVerificationFields(form);\n } else {\n this.stripeElement = await this.mountCardFields(methodId);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n let formattedPayload: StripeV3FormattedPayload;\n let stripeError: StripeError | undefined;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, gatewayId, methodId } = payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const shouldSubmitOrderBeforeLoadingAPM = includes(APM_REDIRECT, methodId);\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n try {\n if (shouldSubmitOrderBeforeLoadingAPM) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n if (gatewayId) {\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n }\n\n const state = this.paymentIntegrationService.getState();\n\n if (isVaultedInstrument(paymentData)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { instrumentId } = paymentData;\n const paymentMethod = state.getPaymentMethodOrThrow(payment.methodId);\n const clientToken = paymentMethod.clientToken;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return await this.executeWithVaulted(\n payment,\n instrumentId,\n shouldSetAsDefaultInstrument,\n clientToken,\n );\n }\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const result = await this.confirmStripePayment(paymentMethod);\n const { clientToken, method } = paymentMethod;\n const { id: token } = result.paymentIntent ?? result.paymentMethod ?? { id: '' };\n\n stripeError = result.error;\n\n formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (method === StripeElementType.CreditCard) {\n formattedPayload.client_token = clientToken;\n }\n\n if (!shouldSubmitOrderBeforeLoadingAPM) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n const paymentPayload = this.buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this.processAdditionalAction(\n this.handleEmptyPaymentIntentError(error, stripeError),\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this.hostedForm) {\n this.hostedForm.detach();\n }\n\n this.isDeinitialize = true;\n this.unmountElement();\n\n return Promise.resolve();\n }\n\n private buildPaymentPayload(\n methodId: string,\n formattedPayload: StripeV3FormattedPayload,\n shouldSetAsDefaultInstrument: boolean | undefined,\n ): Payment {\n const paymentData = shouldSetAsDefaultInstrument\n ? {\n formattedPayload: {\n ...formattedPayload,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n }\n : { formattedPayload };\n\n return { methodId, paymentData };\n }\n\n private isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private isAuthError(stripeError: StripeError | undefined) {\n return stripeError?.code === 'payment_intent_authentication_failure';\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === StripePaymentMethodType.CreditCard;\n }\n\n private isHostedFieldAvailable(): boolean {\n const options = this.getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private async confirmStripePayment(paymentMethod: PaymentMethod): Promise<{\n paymentIntent?: PaymentIntent | undefined;\n paymentMethod?: StripePaymentMethod | undefined;\n error?: StripeError | undefined;\n }> {\n const { clientToken: clientSecret, method, returnUrl } = paymentMethod;\n\n if (!clientSecret) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n switch (method) {\n case StripeElementType.Alipay:\n return this.getStripeJs().confirmAlipayPayment(\n clientSecret,\n { return_url: returnUrl },\n { handleActions: false },\n );\n\n case StripeElementType.IDEAL: {\n const data = this.mapStripePaymentData(StripePaymentMethodType.IDEAL, returnUrl);\n\n return this.getStripeJs().confirmIdealPayment(clientSecret, data, {\n handleActions: false,\n });\n }\n\n case StripeElementType.Sepa: {\n const data = this.mapStripePaymentData(StripePaymentMethodType.Sepa);\n\n return this.getStripeJs().confirmSepaDebitPayment(clientSecret, data);\n }\n\n default: {\n const card = this.useIndividualCardFields\n ? this.getStripeCardElements()[0]\n : this.getStripeElement();\n const billingDetails = this.mapStripeBillingDetails(\n this.paymentIntegrationService.getState().getBillingAddress(),\n this.paymentIntegrationService.getState().getCustomer(),\n );\n\n return this.getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n });\n }\n }\n }\n\n private async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n token: string,\n shouldSetAsDefaultInstrument: boolean | undefined,\n clientToken: string,\n ): Promise {\n const formattedPayload = {\n bigpay_token: { token },\n confirm: true,\n client_token: clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (\n this.isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId) &&\n this.hostedForm\n ) {\n const form = this.hostedForm;\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n payment.paymentData = {\n ...payment.paymentData,\n instrumentId: JSON.stringify({\n token: payment.paymentData?.instrumentId || '',\n client_token: clientToken,\n }),\n };\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this.paymentIntegrationService.loadCurrentOrder();\n }\n\n const paymentPayload = this.buildPaymentPayload(\n payment.methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private getInitializeOptions(): StripeV3PaymentInitializeOptions {\n if (!this.initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.initializeOptions;\n }\n\n private getStripeCardElements(): StripeCardElements {\n if (!this.stripeCardElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeCardElements;\n }\n\n private getStripeElement(): StripeElement {\n if (!this.stripeElement) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeElement;\n }\n\n private getStripeJs(): StripeV3Client {\n if (!this.stripeV3Client) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.stripeV3Client;\n }\n\n private handleEmptyPaymentIntentError(error: unknown, stripeError: StripeError | undefined) {\n if (!isRequestError(error)) {\n return error;\n }\n\n return some(error.body.errors, { code: 'required_field' }) && stripeError\n ? new Error(stripeError.message)\n : error;\n }\n\n private async loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeV3Client) {\n return Promise.resolve(this.stripeV3Client);\n }\n\n return this.scriptLoader.load(\n stripePublishableKey,\n stripeConnectedAccount,\n this.paymentIntegrationService.getState().getLocale(),\n );\n }\n\n private mapStripeAddress(address?: Address): StripeAddress {\n if (address) {\n const {\n city,\n countryCode: country,\n address1: line1,\n address2: line2,\n postalCode,\n stateOrProvinceCode: state,\n } = address;\n\n return { city, country, line1, line2, postal_code: postalCode, state };\n }\n\n return { line1: '' };\n }\n\n private mapStripeBillingDetails(\n billingAddress?: BillingAddress,\n customer?: Customer,\n ): StripeBillingDetails {\n const { firstName, lastName } = billingAddress ||\n customer || { firstName: 'Guest', lastName: '' };\n const name = `${firstName} ${lastName}`.trim();\n const { options } = this.getInitializeOptions();\n\n if (this.useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const { zipCodeElementOptions } = options;\n\n if (zipCodeElementOptions) {\n const postalCode = document.getElementById(zipCodeElementOptions.containerId)\n ? (\n document.getElementById(\n zipCodeElementOptions.containerId,\n ) as HTMLInputElement\n ).value\n : '';\n\n if (postalCode && billingAddress) {\n billingAddress = { ...billingAddress, postalCode };\n }\n }\n }\n\n const address = {\n address: this.mapStripeAddress(billingAddress),\n };\n\n if (customer && customer.addresses[0] && isBillingAddressLike(customer.addresses[0])) {\n const customerAddress = customer.addresses[0];\n const { email } = customer;\n const { phone } = customerAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n if (billingAddress) {\n const { email, phone } = billingAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n return { ...address, name };\n }\n\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.IDEAL,\n returnUrl?: string,\n ): StripeConfirmIdealPaymentData;\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.Sepa,\n ): StripeConfirmSepaPaymentData;\n private mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const customer = this.paymentIntegrationService.getState().getCustomer();\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n\n const result: Partial = {\n payment_method: {\n [stripePaymentMethodType]: this.getStripeElement(),\n billing_details: this.mapStripeBillingDetails(billingAddress, customer),\n },\n };\n\n if (stripePaymentMethodType === StripePaymentMethodType.IDEAL) {\n return { ...result, return_url: returnUrl };\n }\n\n return result;\n }\n\n private mountCardFields(methodId: string): Promise {\n const { options, containerId } = this.getInitializeOptions();\n\n let stripeElement: StripeElement;\n\n return new Promise((resolve, reject) => {\n if (!this.stripeElements) {\n this.stripeElements = this.getStripeJs().elements();\n }\n\n switch (methodId) {\n case StripeElementType.CreditCard:\n if (this.useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const {\n cardNumberElementOptions,\n cardExpiryElementOptions,\n cardCvcElementOptions,\n } = options;\n\n const cardNumberElement =\n this.stripeElements.getElement(StripeElementType.CardNumber) ||\n this.stripeElements.create(\n StripeElementType.CardNumber,\n cardNumberElementOptions,\n );\n const cardExpiryElement =\n this.stripeElements.getElement(StripeElementType.CardExpiry) ||\n this.stripeElements.create(\n StripeElementType.CardExpiry,\n cardExpiryElementOptions,\n );\n const cardCvcElement =\n this.stripeElements.getElement(StripeElementType.CardCvc) ||\n this.stripeElements.create(\n StripeElementType.CardCvc,\n cardCvcElementOptions,\n );\n\n this.stripeCardElements = [\n cardNumberElement,\n cardExpiryElement,\n cardCvcElement,\n ];\n stripeElement = this.stripeCardElements[0];\n\n try {\n cardNumberElement.mount(`#${cardNumberElementOptions.containerId}`);\n cardExpiryElement.mount(`#${cardExpiryElementOptions.containerId}`);\n cardCvcElement.mount(`#${cardCvcElementOptions.containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n } else {\n stripeElement =\n this.stripeElements.getElement(methodId) ||\n this.stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n }\n\n break;\n\n case StripeElementType.IDEAL:\n case StripeElementType.Sepa:\n stripeElement =\n this.stripeElements.getElement(methodId) ||\n this.stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this.isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n\n break;\n\n case StripeElementType.Alipay:\n break;\n }\n\n resolve(stripeElement);\n });\n }\n\n private async mountCardVerificationFields(formOptions: HostedFormOptions): Promise {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const bigpayBaseUrl = storeConfig.paymentSettings.bigpayBaseUrl;\n\n const form = this.paymentIntegrationService.createHostedForm(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private async processAdditionalAction(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!isRequestError(error)) {\n throw error;\n }\n\n const isAdditionalActionError = some(error.body.errors, {\n code: 'additional_action_required',\n });\n const isThreeDSecureRequiredError = some(error.body.errors, {\n code: 'three_d_secure_required',\n });\n\n if (isAdditionalActionError) {\n const action: StripeAdditionalAction = error.body.additional_action_required;\n\n if (action && action.type === 'redirect_to_url') {\n return new Promise(() => {\n if (action.data.redirect_url) {\n window.location.replace(action.data.redirect_url);\n }\n });\n }\n }\n\n if (isThreeDSecureRequiredError) {\n const clientSecret = error.body.three_ds_result.token;\n const needsConfirm = false;\n let catchedConfirmError = false;\n let result;\n\n try {\n result = await this.getStripeJs().confirmCardPayment(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n\n if (result?.error) {\n if (this.isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n if (this.isAuthError(result.error)) {\n throw new StripeV3Error(StripeV3ErrorType.AuthFailure);\n }\n\n throw new Error(result.error.message);\n }\n\n const token = this.getPaymentToken(\n result?.paymentIntent,\n clientSecret,\n catchedConfirmError,\n );\n\n const formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: needsConfirm,\n };\n\n const paymentPayload = this.buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n throw this.handleEmptyPaymentIntentError(error, result?.error);\n }\n }\n\n throw error;\n }\n\n private getPaymentToken(\n paymentIntent: PaymentIntent | undefined,\n clientSecret: string,\n catchedConfirmError: boolean,\n ): string {\n if (!paymentIntent || catchedConfirmError) {\n return clientSecret;\n }\n\n return paymentIntent.id;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this.isHostedFieldAvailable() && this.isHostedPaymentFormEnabled(methodId, gatewayId)\n );\n }\n\n private unmountElement(): void {\n if (this.stripeElement) {\n this.stripeElement.unmount();\n this.stripeElement = undefined;\n }\n }\n}\n","import BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: any): address is BillingAddress {\n return (\n typeof address === 'object' &&\n address !== null &&\n 'id' in address &&\n typeof address.id !== 'undefined'\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { StripeHostWindow, StripeV3Client } from './stripev3';\n\nexport default class StripeV3ScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private stripeWindow: StripeHostWindow = window,\n ) {}\n\n load(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n return this.scriptLoader.loadScript('https://js.stripe.com/v3/').then(() => {\n if (!this.stripeWindow.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.stripeWindow.Stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: ['payment_intent_beta_3', 'alipay_pm_beta_1'],\n apiVersion: '2020-03-02;alipay_beta=v1',\n });\n });\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeV3PaymentStrategy from './stripev3-payment-strategy';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst createStripeV3PaymentStrategy: PaymentStrategyFactory = (paymentIntegrationService) => {\n return new StripeV3PaymentStrategy(\n paymentIntegrationService,\n new StripeV3ScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createStripeV3PaymentStrategy, [{ gateway: 'stripev3' }]);\n","import { includes, some } from 'lodash';\n\nimport {\n Address,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isStripeError } from './is-stripe-error';\nimport {\n AddressOptions,\n StripeAdditionalActionRequired,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeStringConstants,\n StripeUPEClient,\n StripeUPEPaymentIntentStatus,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions from './stripe-upe-initialize-options';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nexport default class StripeUPEIntegrationService {\n private isMounted = false;\n private checkoutEventsUnsubscribe?: () => void;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n ) {}\n\n deinitialize(): void {\n this.checkoutEventsUnsubscribe?.();\n this.isMounted = false;\n }\n\n initCheckoutEventsSubscription(\n gatewayId: string,\n methodId: string,\n stripeupe: StripeUPEPaymentInitializeOptions,\n stripeElements?: StripeElements,\n ): void {\n this.checkoutEventsUnsubscribe = this.paymentIntegrationService.subscribe(\n async () => {\n const paymentElement = stripeElements?.getElement(StripeElementType.PAYMENT);\n\n if (!paymentElement) {\n return;\n }\n\n try {\n await this.updateStripePaymentIntent(gatewayId, methodId);\n } catch (error) {\n if (this.isMounted) {\n paymentElement.unmount();\n this.isMounted = false;\n }\n\n if (error instanceof Error) {\n stripeupe.onError?.(error);\n }\n\n return;\n }\n\n if (!this.isMounted) {\n await stripeElements?.fetchUpdates();\n this.mountElement(paymentElement, stripeupe.containerId);\n }\n },\n (state) => state.getCheckout()?.outstandingBalance,\n (state) => state.getCheckout()?.coupons,\n );\n }\n\n mountElement(stripeElement: StripeElement, containerId: string): void {\n if (!document.getElementById(containerId)) {\n return;\n }\n\n stripeElement.mount(`#${containerId}`);\n this.isMounted = true;\n }\n\n mapAppearanceVariables(styles: NonNullable) {\n return {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n colorIcon: styles.fieldPlaceholderText,\n };\n }\n\n mapInputAppearanceRules(styles: NonNullable) {\n return {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n };\n }\n\n throwStripeError(stripeError?: unknown): never {\n if (isStripeError(stripeError)) {\n this.throwDisplayableStripeError(stripeError);\n\n if (this.isCancellationError(stripeError)) {\n throw new PaymentMethodCancelledError();\n }\n }\n\n throw new PaymentMethodFailedError();\n }\n\n throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n\n isCancellationError(stripeError?: StripeError): boolean {\n const errorMessage = stripeError?.payment_intent.last_payment_error?.message;\n\n return !!errorMessage && errorMessage.indexOf('canceled') !== -1;\n }\n\n throwPaymentConfirmationProceedMessage() {\n // INFO: for case if payment was successfully confirmed on Stripe side but on BC side something go wrong, request failed and order status hasn't changed yet\n // For shopper we need to show additional message that BC is waiting for stripe confirmation, to prevent additional payment creation\n throw new PaymentMethodFailedError(\n \"We've received your order and are processing your payment. Once the payment is verified, your order will be completed. We will send you an email when it's completed. Please note, this process may take a few minutes depending on the processing times of your chosen method.\",\n );\n }\n\n async isPaymentCompleted(\n methodId: string,\n stripeUPEClient?: StripeUPEClient,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { features } = state.getStoreConfigOrThrow().checkoutSettings;\n\n if (\n !paymentMethod.clientToken ||\n !stripeUPEClient ||\n !features['PI-626.Block_unnecessary_payment_confirmation_for_StripeUPE']\n ) {\n return false;\n }\n\n const { paymentIntent } = await stripeUPEClient.retrievePaymentIntent(\n paymentMethod.clientToken,\n );\n\n return paymentIntent?.status === StripeUPEPaymentIntentStatus.SUCCEEDED;\n }\n\n mapStripePaymentData(\n stripeElements?: StripeElements,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const billingAddress = this.paymentIntegrationService.getState().getBillingAddress();\n const { firstName, lastName, email } = billingAddress || {};\n const address = this._mapStripeAddress(billingAddress);\n\n if (!stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!email || !address || !address.city || !address.country || !firstName || !lastName) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n elements: stripeElements,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n payment_method_data: {\n billing_details: {\n email,\n address,\n name: `${firstName} ${lastName}`,\n },\n },\n ...(returnUrl && { return_url: returnUrl }),\n },\n };\n }\n\n isAdditionalActionError(errors: Array<{ code: string }>): boolean {\n return some(errors, { code: 'additional_action_required' });\n }\n\n isRedirectAction(additionalAction: StripeAdditionalActionRequired): boolean {\n const {\n type,\n data: { redirect_url },\n } = additionalAction;\n\n return type === 'redirect_to_url' && !!redirect_url;\n }\n\n isOnPageAdditionalAction(additionalAction: StripeAdditionalActionRequired): boolean {\n const {\n type,\n data: { token },\n } = additionalAction;\n\n return type === 'additional_action_requires_payment_method' && !!token;\n }\n\n async updateStripePaymentIntent(gatewayId: string, methodId: string): Promise {\n // INFO: to trigger payment intent update on the BE side we need to make stripe config request\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.scriptLoader.updateStripeElements({ clientSecret: clientToken });\n }\n\n private _mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const { city, address1, address2, countryCode: country, postalCode } = address;\n\n return {\n city,\n country,\n postal_code: postalCode,\n line1: address1,\n line2: address2,\n };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n}\n","import { StripeError } from './stripe-upe';\n\nexport function isStripeError(error: unknown): error is StripeError {\n return typeof error === 'object' && error !== null && 'type' in error;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n ar: ['ar'],\n bg: ['bg'],\n cs: ['cs'],\n da: ['da'],\n de: ['de'],\n el: ['el'],\n en: ['en', 'en-GB'],\n es: ['es', 'es-419'],\n et: ['et'],\n fi: ['fi'],\n fil: ['fil'],\n fr: ['fr', 'fr-CA'],\n he: ['he'],\n hr: ['hr'],\n hu: ['hu'],\n id: ['id'],\n it: ['it'],\n ja: ['ja'],\n ko: ['ko'],\n lt: ['lt'],\n lv: ['lv'],\n ms: ['ms'],\n mt: ['mt'],\n nb: ['nb'],\n nl: ['nl'],\n pl: ['pl'],\n pt: ['pt', 'pt-BR'],\n ro: ['ro'],\n ru: ['ru'],\n sk: ['sk'],\n sl: ['sl'],\n sv: ['sv'],\n th: ['th'],\n tr: ['tr'],\n vi: ['vi'],\n zh: ['zh', 'zh-HK', 'zh-TW'],\n};\n","import { supportedLocales } from './stripe-upe-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace(/_/g, '-').toLowerCase().split('-');\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'auto';\n }\n\n const formattedLocale = country ? `${language}-${country.toUpperCase()}` : language;\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { includes, some } from 'lodash';\n\nimport {\n FormattedHostedInstrument,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n RequestError,\n StripeUPEIntent,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport formatLocale from './format-locale';\nimport isStripeAcceleratedCheckoutCustomer from './is-stripe-accelerated-checkout-customer';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeAdditionalActionRequired,\n StripeElement,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeElementUpdateOptions,\n StripeError,\n StripeEventType,\n StripePaymentMethodType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n StripeUPEInitializationData,\n StripeUpeResult,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst APM_REDIRECT = [\n StripePaymentMethodType.SOFORT,\n StripePaymentMethodType.EPS,\n StripePaymentMethodType.GRABPAY,\n StripePaymentMethodType.BANCONTACT,\n StripePaymentMethodType.IDEAL,\n StripePaymentMethodType.GIROPAY,\n StripePaymentMethodType.ALIPAY,\n StripePaymentMethodType.KLARNA,\n];\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private _isStripeElementUpdateEnabled?: boolean;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n private stripeUPEIntegrationService: StripeUPEIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeUPEPaymentInitializeOptions,\n ): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._loadStripeElement(stripeupe, gatewayId, methodId).catch((error) =>\n stripeupe.onError?.(error),\n );\n\n this.stripeUPEIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeupe,\n this._stripeElements,\n );\n\n return Promise.resolve();\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData, methodId, gatewayId } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const state = this.paymentIntegrationService.getState();\n const { isStoreCreditApplied: useStoreCredit } = state.getCheckoutOrThrow();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const stripePaymentProviderCustomer = isStripeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const stripeLinkAuthenticationState =\n stripePaymentProviderCustomer.stripeLinkAuthenticationState;\n\n if (useStoreCredit) {\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n }\n\n if (gatewayId) {\n await this.stripeUPEIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n const { email } = state.getCustomerOrThrow();\n\n if (stripeLinkAuthenticationState !== undefined && !email) {\n const billingAddress = state.getBillingAddressOrThrow();\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n }\n\n if (isVaultedInstrument(paymentData)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { instrumentId } = paymentData;\n\n await this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n const { initializationData } =\n state.getPaymentMethodOrThrow(methodId);\n const { newConfirmationFlow } = initializationData || {};\n\n if (newConfirmationFlow) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithStripeConfirmation(\n payment.methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n\n if (includes(APM_REDIRECT, methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithAPM(payment.methodId);\n\n return;\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n await this._executeWithoutRedirect(\n payment.methodId,\n stripeLinkAuthenticationState ? false : shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this.stripeUPEIntegrationService.deinitialize();\n this._stripeElements = undefined;\n this._stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _executeWithStripeConfirmation(\n methodId: string,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(\n methodId,\n clientToken || '',\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalActionWithStripeConfirmation(\n error,\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _executeWithAPM(methodId: string): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(methodId, paymentMethod.clientToken || '');\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processAdditionalAction(error, methodId);\n }\n }\n\n private async _executeWithoutRedirect(\n methodId: string,\n shouldSaveInstrument: boolean,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentMethod.clientToken || '',\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processAdditionalAction(\n error,\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _executeWithVaulted(\n methodId: string,\n token: string,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const cartId = state.getCart()?.id;\n\n try {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n cart_id: cartId,\n bigpay_token: { token },\n confirm: false,\n client_token: paymentMethod.clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n return this._processVaultedAdditionalAction(\n error,\n methodId,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _loadStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const { containerId, style, render, initStripeElementUpdateTrigger } = stripeupe;\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { checkoutSettings } = state.getStoreConfigOrThrow();\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n this._isStripeElementUpdateEnabled =\n !!checkoutSettings.features['PI-1679.trigger_update_stripe_payment_element'] &&\n typeof initStripeElementUpdateTrigger === 'function';\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: this.stripeUPEIntegrationService.mapAppearanceVariables(style),\n rules: {\n '.Input': this.stripeUPEIntegrationService.mapInputAppearanceRules(styles),\n },\n };\n }\n\n this._stripeElements = await this.scriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatLocale(shopperLanguage),\n appearance,\n });\n\n const { getBillingAddress, getShippingAddress } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this._stripeElements.getElement(StripeElementType.PAYMENT) ||\n this._stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n ...this._getStripeElementTerms(),\n });\n\n this.stripeUPEIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on('ready', () => {\n render();\n });\n\n stripeElement.on('change', (event: StripeEventType) => {\n if (!event?.value || !('type' in event.value)) {\n return;\n }\n\n this._updateStripeLinkStateByElementType(event.value.type);\n });\n\n if (this._isStripeElementUpdateEnabled) {\n initStripeElementUpdateTrigger?.(this._updateStripeElement.bind(this));\n }\n }\n\n private async _processAdditionalActionWithStripeConfirmation(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { data: additionalActionData } = error.body.additional_action_required;\n const { token } = additionalActionData;\n\n const { paymentIntent } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n paymentIntent?.id || token,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this._stripeUPEClient?.confirmPayment(stripePaymentData)\n : await this._stripeUPEClient?.retrievePaymentIntent(token || '');\n\n stripeError = confirmationResult?.error;\n\n if (stripeError || !confirmationResult?.paymentIntent) {\n throw new PaymentMethodFailedError();\n }\n\n return confirmationResult;\n } catch (error: unknown) {\n this.stripeUPEIntegrationService.throwStripeError(stripeError);\n }\n }\n\n // TODO: complexity of _processAdditionalAction method\n\n private async _processAdditionalAction(\n error: unknown,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!isRequestError(error)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)) {\n const {\n data: { token, redirect_url },\n } = error.body.additional_action_required;\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n if (\n this.stripeUPEIntegrationService.isRedirectAction(\n error.body.additional_action_required,\n ) &&\n !isPaymentCompleted\n ) {\n const { paymentIntent, error: stripeError } =\n await this._stripeUPEClient.confirmPayment(\n this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n redirect_url,\n ),\n );\n\n if (stripeError) {\n this.stripeUPEIntegrationService.throwDisplayableStripeError(stripeError);\n throw new PaymentMethodFailedError();\n }\n\n if (!paymentIntent) {\n throw new RequestError();\n }\n } else if (\n this.stripeUPEIntegrationService.isOnPageAdditionalAction(\n error.body.additional_action_required,\n )\n ) {\n let result;\n let catchedConfirmError = false;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this._stripeElements,\n );\n const isPaymentCompleted =\n await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this._stripeUPEClient,\n );\n\n try {\n result = !isPaymentCompleted\n ? await this._stripeUPEClient.confirmPayment(stripePaymentData)\n : await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this.stripeUPEIntegrationService.throwDisplayableStripeError(result.error);\n\n if (this.stripeUPEIntegrationService.isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n catchedConfirmError ? token : result?.paymentIntent?.id,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n }\n\n throw error;\n }\n\n private async _processVaultedAdditionalAction(\n error: unknown,\n methodId?: string,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (\n !methodId ||\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this._stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this.stripeUPEIntegrationService.throwStripeError(result.error);\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = this._getPaymentPayload(\n methodId,\n catchedConfirmError ? clientSecret : result?.paymentIntent?.id,\n false,\n shouldSetAsDefaultInstrument,\n );\n\n return this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _getPaymentPayload(\n methodId: string,\n token: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const formattedPayload: StripeUPEIntent & FormattedHostedInstrument = {\n cart_id: cartId,\n credit_card_token: { token },\n confirm: false,\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private _updateStripeElement({ shouldShowTerms }: StripeElementUpdateOptions): void {\n const stripeElement = this._stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.update({\n ...this._getStripeElementTerms(shouldShowTerms),\n });\n }\n\n private _getStripeElementTerms(\n shouldShowTerms?: boolean,\n ): Pick {\n let card = StripeStringConstants.AUTO;\n\n if (this._isStripeElementUpdateEnabled) {\n card = shouldShowTerms ? StripeStringConstants.AUTO : StripeStringConstants.NEVER;\n }\n\n return {\n terms: {\n card,\n },\n };\n }\n\n private _updateStripeLinkStateByElementType(paymentElementType: StripePaymentMethodType): void {\n const state = this.paymentIntegrationService.getState();\n const paymentProviderCustomer = state.getPaymentProviderCustomerOrThrow();\n const isStripeLinkElementType = paymentElementType === StripePaymentMethodType.Link;\n\n // INFO: Trigger additional update only if Stripe Link Authentication was skipped on the customer step, but the Link payment element was rendered.\n if (\n !isStripeAcceleratedCheckoutCustomer(paymentProviderCustomer) &&\n isStripeLinkElementType\n ) {\n this.paymentIntegrationService.updatePaymentProviderCustomer({\n stripeLinkAuthenticationState: isStripeLinkElementType,\n });\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEPaymentStrategy from './stripe-upe-payment-strategy';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeUPEPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeUPEScriptLoader(getScriptLoader());\n\n return new StripeUPEPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeUPEIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeUPEPaymentStrategy, [\n { gateway: 'stripeupe' },\n { gateway: 'stripeupe', id: 'klarna' },\n]);\n","import { StripePaymentEvent } from './stripe-upe';\n\nexport const isStripePaymentEvent = (event: unknown): event is StripePaymentEvent => {\n return typeof event === 'object' && event !== null && 'value' in event && 'collapsed' in event;\n};\n","import {\n InvalidArgumentError,\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport formatLocale from './format-locale';\nimport { isStripePaymentEvent } from './is-stripe-payment-event';\nimport { isStripeUPEPaymentMethodLike } from './is-stripe-upe-payment-method-like';\nimport {\n StripeAdditionalActionRequired,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripeEventType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n StripeUpeResult,\n} from './stripe-upe';\nimport StripeUPEPaymentInitializeOptions, {\n WithStripeUPEPaymentInitializeOptions,\n} from './stripe-upe-initialize-options';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nexport default class StripeOCSPaymentStrategy implements PaymentStrategy {\n private stripeUPEClient?: StripeUPEClient;\n private stripeElements?: StripeElements;\n private selectedMethodId?: string;\n private readonly stripeSVGSizeCoefficient = 0.88;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private scriptLoader: StripeUPEScriptLoader,\n private stripeUPEIntegrationService: StripeUPEIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithStripeUPEPaymentInitializeOptions,\n ): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n try {\n await this._initializeStripeElement(stripeupe, gatewayId, methodId);\n } catch (error) {\n if (error instanceof Error) {\n stripeupe.onError?.(error);\n }\n }\n\n this.stripeUPEIntegrationService.initCheckoutEventsSubscription(\n gatewayId,\n methodId,\n stripeupe,\n this.stripeElements,\n );\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n const { methodId, gatewayId } = payment || {};\n\n if (!this.stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" or \"methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n\n if (isStoreCreditApplied) {\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n }\n\n await this.stripeUPEIntegrationService.updateStripePaymentIntent(gatewayId, methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n const { clientToken } = state.getPaymentMethodOrThrow(methodId);\n const paymentPayload = this._getPaymentPayload(methodId, clientToken || '');\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n await this._processAdditionalAction(error, methodId);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this.stripeUPEIntegrationService.deinitialize();\n this.stripeElements = undefined;\n this.stripeUPEClient = undefined;\n\n return Promise.resolve();\n }\n\n private async _initializeStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const state = await this.paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n if (!isStripeUPEPaymentMethodLike(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n const { containerId, style, render, paymentMethodSelect, handleClosePaymentMethod } =\n stripeupe;\n\n this.stripeElements = await this.scriptLoader.getElements(this.stripeUPEClient, {\n clientSecret: clientToken,\n locale: formatLocale(shopperLanguage),\n appearance: this._getElementAppearance(style),\n fonts: [\n {\n cssSrc: 'https://fonts.googleapis.com/css?family=Montserrat:700,500,400%7CKarla:400&display=swap', // TODO: get style from theme\n },\n ],\n });\n\n const { getBillingAddress, getShippingAddress } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this.stripeElements.getElement(StripeElementType.PAYMENT) ||\n this.stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n layout: {\n type: 'accordion',\n defaultCollapsed: false,\n radios: true,\n spacedAccordionItems: false,\n visibleAccordionItemsCount: 0,\n },\n });\n\n this.stripeUPEIntegrationService.mountElement(stripeElement, containerId);\n\n stripeElement.on('ready', () => {\n render();\n });\n\n stripeElement.on('change', (event: StripeEventType) => {\n this._onStripeElementChange(event, gatewayId, methodId, paymentMethodSelect);\n });\n\n handleClosePaymentMethod?.(this._collapseStripeElement.bind(this));\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this.stripeUPEClient) {\n return this.stripeUPEClient;\n }\n\n return this.scriptLoader.getStripeClient(stripePublishableKey, stripeConnectedAccount);\n }\n\n private _getElementAppearance(\n style?: StripeUPEPaymentInitializeOptions['style'],\n ): StripeUPEAppearanceOptions | undefined {\n if (!style) {\n return;\n }\n\n const titleFontSize = '15px'; // TODO: get style from theme\n const titleFontWeight = '700'; // TODO: get style from theme\n const titleColor = '#5f5f5f'; // TODO: get style from theme\n const radioColor = '#ddd'; // TODO: get style from theme\n const radioFocusColor = '#4496f6'; // TODO: get style from theme\n const { radioIconOuterWidth, radioIconOuterStrokeWidth, radioIconInnerWidth } = style;\n const radioIconSize = this._getRadioIconSizes(\n radioIconOuterWidth,\n radioIconOuterStrokeWidth,\n radioIconInnerWidth,\n );\n\n return {\n variables: {\n ...this.stripeUPEIntegrationService.mapAppearanceVariables(style),\n fontFamily: 'Montserrat, Arial, Helvetica', // TODO: get style from theme\n },\n rules: {\n '.Input': this.stripeUPEIntegrationService.mapInputAppearanceRules(style),\n '.AccordionItem': {\n borderRadius: 0,\n borderWidth: 0,\n borderBottomWidth: '1px',\n boxShadow: 'none',\n fontSize: titleFontSize,\n fontWeight: titleFontWeight,\n padding: '13px 20px 13px 18px',\n },\n '.TabLabel, .AccordionItem': {\n fontSize: titleFontSize,\n fontWeight: titleFontWeight,\n color: titleColor,\n },\n '.TabLabel--selected, .AccordionItem--selected': {\n fontWeight: titleFontWeight,\n color: titleColor,\n },\n '.RadioIcon': {\n width: radioIconSize.outerWidth,\n },\n '.RadioIconOuter': {\n strokeWidth: radioIconSize.outerStrokeWidth,\n stroke: radioColor,\n },\n '.RadioIconOuter--checked': {\n stroke: radioFocusColor,\n },\n '.RadioIconInner': {\n r: radioIconSize.innerRadius,\n fill: radioFocusColor,\n },\n },\n };\n }\n\n private _getRadioIconSizes(\n realOuterWidth: string | number = 26,\n realOuterStrokeWidth: string | number = 1,\n realInnerWidth: string | number = 17,\n ) {\n const percentageCoefficient = this.stripeSVGSizeCoefficient * 100;\n\n const outerWidth =\n typeof realOuterWidth === 'string' ? parseInt(realOuterWidth, 10) : realOuterWidth;\n const outerStrokeWidth =\n typeof realOuterStrokeWidth === 'string'\n ? parseInt(realOuterStrokeWidth, 10)\n : realOuterStrokeWidth;\n const innerWidth =\n typeof realInnerWidth === 'string' ? parseInt(realInnerWidth, 10) : realInnerWidth;\n\n const stripeEqualOuterWidth = (outerWidth / this.stripeSVGSizeCoefficient).toFixed(2);\n const stripeEqualOuterStrokeWidth = (\n (outerStrokeWidth / outerWidth) *\n percentageCoefficient\n ).toFixed(2);\n const stripeEqualInnerRadius = (\n ((innerWidth / outerWidth) * percentageCoefficient) /\n 2\n ).toFixed(2);\n\n return {\n outerWidth: `${stripeEqualOuterWidth}px`,\n outerStrokeWidth: `${stripeEqualOuterStrokeWidth}px`,\n innerRadius: `${stripeEqualInnerRadius}px`,\n };\n }\n\n private _collapseStripeElement() {\n const stripeElement = this.stripeElements?.getElement(StripeElementType.PAYMENT);\n\n stripeElement?.collapse();\n }\n\n private _getPaymentPayload(methodId: string, token: string): Payment {\n const cartId = this.paymentIntegrationService.getState().getCart()?.id || '';\n const formattedPayload = {\n cart_id: cartId,\n credit_card_token: { token },\n confirm: false,\n payment_method_id: this.selectedMethodId,\n };\n\n return {\n methodId,\n paymentData: {\n formattedPayload,\n },\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n methodId: string,\n ): Promise {\n if (\n !isRequestError(error) ||\n !this.stripeUPEIntegrationService.isAdditionalActionError(error.body.errors)\n ) {\n throw error;\n }\n\n if (!this.stripeUPEClient || !this.stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { data: additionalActionData } = error.body.additional_action_required;\n const { token } = additionalActionData;\n\n const { paymentIntent } = await this._confirmStripePaymentOrThrow(\n methodId,\n additionalActionData,\n );\n\n const paymentPayload = this._getPaymentPayload(methodId, paymentIntent?.id || token);\n\n try {\n return await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error) {\n this.stripeUPEIntegrationService.throwPaymentConfirmationProceedMessage();\n }\n }\n\n private async _confirmStripePaymentOrThrow(\n methodId: string,\n additionalActionData: StripeAdditionalActionRequired['data'],\n ): Promise {\n const { token, redirect_url } = additionalActionData;\n const stripePaymentData = this.stripeUPEIntegrationService.mapStripePaymentData(\n this.stripeElements,\n redirect_url,\n );\n let stripeError: StripeError | undefined;\n\n try {\n const isPaymentCompleted = await this.stripeUPEIntegrationService.isPaymentCompleted(\n methodId,\n this.stripeUPEClient,\n );\n\n const confirmationResult = !isPaymentCompleted\n ? await this.stripeUPEClient?.confirmPayment(stripePaymentData)\n : await this.stripeUPEClient?.retrievePaymentIntent(token || '');\n\n stripeError = confirmationResult?.error;\n\n if (stripeError || !confirmationResult?.paymentIntent) {\n throw new PaymentMethodFailedError();\n }\n\n return confirmationResult;\n } catch (error: unknown) {\n this.stripeUPEIntegrationService.throwStripeError(stripeError);\n }\n }\n\n private _onStripeElementChange(\n event: StripeEventType,\n gatewayId: string,\n methodId: string,\n paymentMethodSelect?: (id: string) => void,\n ) {\n if (!isStripePaymentEvent(event) || event.collapsed) {\n return;\n }\n\n this.selectedMethodId = event.value.type;\n paymentMethodSelect?.(`${gatewayId}-${methodId}`);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport StripeOCSPaymentStrategy from './stripe-ocs-payment-strategy';\nimport StripeUPEIntegrationService from './stripe-upe-integration-service';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createStripeOCSPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const stripeScriptLoader = new StripeUPEScriptLoader(getScriptLoader());\n\n return new StripeOCSPaymentStrategy(\n paymentIntegrationService,\n stripeScriptLoader,\n new StripeUPEIntegrationService(paymentIntegrationService, stripeScriptLoader),\n );\n};\n\nexport default toResolvableModule(createStripeOCSPaymentStrategy, [\n { gateway: 'stripeupe', id: 'stripe_ocs' },\n]);\n","import { RequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface TdOnlineMartHostWindow extends Window {\n customcheckout?(): TDCustomCheckoutSDK;\n}\n\nexport interface TDCustomCheckoutSDK {\n create(fieldType: FieldType, options?: FieldOptions): TdOnlineMartElement;\n createToken(callback: (result: CreateTokenResponse) => void): void;\n}\n\nexport interface TdOnlineMartElement {\n mount(cssSelector: string): void;\n unmount(): void;\n}\n\nexport enum FieldType {\n CARD_NUMBER = 'card-number',\n CVV = 'cvv',\n EXPIRY = 'expiry',\n}\n\nexport interface TDOnlineMartInput {\n id: string;\n fieldType: FieldType;\n inputElement?: TdOnlineMartElement;\n}\n\ninterface CreateTokenResponse {\n code: string;\n error?: CreateTokenError;\n token?: string;\n last4?: string;\n expiryMonth?: string;\n expiryYear?: string;\n}\n\nexport interface CreateTokenError {\n field: string;\n type: string;\n message: string;\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport interface TdOnlineMartThreeDSErrorBody {\n errors?: Array<{ code: string }>;\n three_ds_result?: {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n };\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type TdOnlineMartAdditionalAction = RequestError;\n\n// Note: The style property affects the remote styling of text inside the iframe input. The classes property updates the class list of the element the field is mounted to on your page.\ninterface FieldOptions {\n placeholder?: string;\n style?: Styles;\n classes?: Classes;\n brands?: string[];\n}\n\ninterface Classes {\n base?: string;\n complete?: string;\n empty?: string;\n focus?: string;\n error?: string;\n}\n\ninterface Styles {\n base?: CssStyles;\n complete?: CssStyles;\n empty?: CssStyles;\n error?: CssStyles;\n}\n\ninterface CssStyles {\n color?: string;\n fontFamily?: string;\n fontSize?: string;\n fontStyle?: string;\n fontWeight?: string;\n textDecoration?: string;\n padding?: string;\n paddingLeft?: string;\n paddingTop?: string;\n paddingRight?: string;\n paddingBottom?: string;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isCreateTokenError from './is-create-token-error';\nimport { isTdOnlineMartAdditionalAction } from './isTdOnlineMartAdditionalAction';\nimport {\n FieldType,\n TDCustomCheckoutSDK,\n TDOnlineMartInput,\n TdOnlineMartThreeDSErrorBody,\n} from './td-online-mart';\nimport TDOnlineMartScriptLoader from './td-online-mart-script-loader';\n\nexport default class TDOnlineMartPaymentStrategy implements PaymentStrategy {\n private tdOnlineMartClient?: TDCustomCheckoutSDK;\n private tdInputs: TDOnlineMartInput[] = [\n {\n id: 'ccNumber',\n fieldType: FieldType.CARD_NUMBER,\n },\n {\n id: 'ccCvv',\n fieldType: FieldType.CVV,\n },\n {\n id: 'ccExpiry',\n fieldType: FieldType.EXPIRY,\n },\n ];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private tdOnlineMartScriptLoader: TDOnlineMartScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.tdOnlineMartClient = await this.loadTDOnlineMartJs();\n\n this.mountHostedFields(methodId);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!payment.methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paymentPayload = await this.getPaymentPayloadOrThrow(payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n } catch (error: unknown) {\n await this.processWithAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.tdOnlineMartClient = undefined;\n\n this.tdInputs.forEach(({ inputElement }: TDOnlineMartInput) => {\n inputElement?.unmount();\n });\n\n return Promise.resolve();\n }\n\n private async getPaymentPayloadOrThrow(payment: OrderPaymentRequestBody) {\n const { methodId, paymentData } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const commonPaymentData = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n browser_info: getBrowserInfo(),\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n paymentData.instrumentId\n ) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const digitalItemsInCart = !!cart.lineItems.digitalItems.length;\n\n const shouldAddVerificationToken =\n !this.isTrustedVaultingInstrument(paymentData.instrumentId) || digitalItemsInCart;\n\n return {\n methodId,\n paymentData: {\n ...commonPaymentData,\n instrumentId: paymentData.instrumentId,\n ...(shouldAddVerificationToken ? { nonce: paymentData.instrumentId } : {}),\n },\n };\n }\n\n let nonce: string;\n\n try {\n nonce = await this.getTokenOrThrow();\n } catch (error) {\n this.throwTokenizationError(error);\n }\n\n return {\n methodId,\n paymentData: {\n ...commonPaymentData,\n nonce,\n },\n };\n }\n\n private mountHostedFields(methodId: string): void {\n const options = this.getHostedFieldsOptions();\n const tdOnlineMartClient = this.getTDOnlineMartClientOrThrow();\n\n this.tdInputs.forEach((input: TDOnlineMartInput) => {\n const inputId = `${methodId}-${input.id}`;\n\n if (!document.getElementById(inputId)) {\n return;\n }\n\n input.inputElement = tdOnlineMartClient.create(input.fieldType, options);\n input.inputElement.mount(`#${inputId}`);\n });\n }\n\n private async loadTDOnlineMartJs(): Promise {\n if (this.tdOnlineMartClient) {\n return this.tdOnlineMartClient;\n }\n\n return this.tdOnlineMartScriptLoader.load();\n }\n\n private getTokenOrThrow(): Promise {\n return new Promise((resolve, reject) => {\n this.getTDOnlineMartClientOrThrow().createToken((result) => {\n const { error, token } = result;\n\n if (error || !token) {\n return reject(error);\n }\n\n resolve(token);\n });\n });\n }\n\n private getTDOnlineMartClientOrThrow(): TDCustomCheckoutSDK {\n if (!this.tdOnlineMartClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.tdOnlineMartClient;\n }\n\n private async processWithAdditionalAction(error: unknown): Promise {\n if (!isTdOnlineMartAdditionalAction(error)) {\n throw error;\n }\n\n const { three_ds_result: threeDSResult }: TdOnlineMartThreeDSErrorBody = error.body;\n const {\n acs_url: formUrl,\n payer_auth_request: threeDSSessionData,\n merchant_data: creq,\n } = threeDSResult || {};\n\n if (!formUrl || !threeDSSessionData || !creq) {\n throw new PaymentArgumentInvalidError(['formUrl', 'threeDSSessionData', 'creq']);\n }\n\n return new Promise((resolve) => {\n this.formPoster.postForm(\n formUrl,\n {\n threeDSSessionData,\n creq,\n },\n resolve,\n '_top',\n );\n });\n }\n\n private throwTokenizationError(error: unknown): never {\n if (!isCreateTokenError(error)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n throw new Error(error.message);\n }\n\n private getHostedFieldsOptions() {\n const style = {\n error: {\n color: '#d14343',\n },\n };\n\n const classes = {\n error: 'form-input--error',\n };\n\n return {\n style,\n classes,\n };\n }\n\n private isTrustedVaultingInstrument(instrumentId: string): boolean {\n const instruments = this.paymentIntegrationService.getState().getInstruments();\n\n const { trustedShippingAddress } =\n instruments?.find(({ bigpayToken }) => bigpayToken === instrumentId) || {};\n\n return !!trustedShippingAddress;\n }\n}\n","import { isArray, isObject, some } from 'lodash';\n\nimport { isRequestError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TdOnlineMartAdditionalAction, TdOnlineMartThreeDSErrorBody } from './td-online-mart';\n\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nfunction isTdOnlineMartThreeDSErrorBody(\n errorBody: unknown,\n): errorBody is TdOnlineMartThreeDSErrorBody {\n return (\n isObject(errorBody) &&\n typeof errorBody === 'object' &&\n 'errors' in errorBody &&\n 'three_ds_result' in errorBody &&\n isArray((errorBody as TdOnlineMartThreeDSErrorBody).errors) &&\n some((errorBody as TdOnlineMartThreeDSErrorBody).errors, {\n code: 'three_d_secure_required',\n })\n );\n}\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n\nexport function isTdOnlineMartAdditionalAction(\n error: unknown,\n): error is TdOnlineMartAdditionalAction {\n return isRequestError(error) && isTdOnlineMartThreeDSErrorBody(error.body);\n}\n","import { CreateTokenError } from './td-online-mart';\n\nexport default function isCreateTokenError(error: unknown): error is CreateTokenError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'field' in error &&\n 'type' in error &&\n 'message' in error\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { TDCustomCheckoutSDK, TdOnlineMartHostWindow } from './td-online-mart';\n\nexport default class TDOnlineMartScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private tdOnlineMartWindow: TdOnlineMartHostWindow = window,\n ) {}\n\n async load(): Promise {\n if (!this.tdOnlineMartWindow.customcheckout) {\n await this.scriptLoader.loadScript(\n 'https://libs.na.bambora.com/customcheckout/1/customcheckout.js',\n );\n }\n\n if (!this.tdOnlineMartWindow.customcheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.tdOnlineMartWindow.customcheckout();\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport TDOnlineMartPaymentStrategy from './td-online-mart-payment-strategy';\nimport TDOnlineMartScriptLoader from './td-online-mart-script-loader';\n\nconst createTDOnlineMartPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new TDOnlineMartPaymentStrategy(\n paymentIntegrationService,\n new TDOnlineMartScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createTDOnlineMartPaymentStrategy, [{ id: 'tdonlinemart' }]);\n","import { merge, some } from 'lodash';\n\nimport { CreditCardPaymentStrategy } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n isRequestError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n WithWorldpayAccessPaymentInitializeOptions,\n WorldpayAccess3DSOptions,\n WorldpayAccessAdditionalAction,\n WorldpayAccessPaymentInitializeOptions,\n} from './worldpayaccess-payment-options';\n\nconst IFRAME_NAME = 'worldpay_hosted_payment_page';\nconst IFRAME_HIDDEN_NAME = 'worldpay_hosted_hidden_payment_page';\nconst PAYMENT_CANNOT_CONTINUE = 'Payment cannot continue';\n\nlet submit: (paymentPayload: OrderPaymentRequestBody) => Promise;\n\nexport default class WorldpayAccessPaymentStrategy extends CreditCardPaymentStrategy {\n private _initializeOptions?: WorldpayAccessPaymentInitializeOptions;\n\n async initialize(\n options?: PaymentInitializeOptions & WithWorldpayAccessPaymentInitializeOptions,\n ): Promise {\n this._initializeOptions = options && options.worldpay;\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return super.initialize(options);\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n submit = this._submitAdditionalAction();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n return await super.execute(orderRequest, options);\n } catch (error) {\n return this._processAdditionalAction(error, payment);\n }\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise((resolve, reject) => {\n const messageEvent = async (event: MessageEvent) => {\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEvent);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n iframeHidden.remove();\n\n const data = JSON.parse(event.data);\n const paymentPayload = merge({}, payment, {\n paymentData: { threeDSecure: { token: data.SessionId } },\n });\n\n try {\n resolve(await submit(paymentPayload));\n } catch (submitError) {\n if (\n !isRequestError(submitError) ||\n !some(submitError.body.errors, { code: 'three_d_secure_required' })\n ) {\n return reject(submitError);\n }\n\n if (!this._initializeOptions) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n const { onLoad } = this._initializeOptions;\n\n const frame = this._createIframe(submitError.body.three_ds_result);\n\n try {\n onLoad(frame, () => reject(new Error('Payment was cancelled')));\n } catch (onLoadError) {\n reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n }\n };\n\n window.addEventListener('message', messageEvent);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('message', messageEvent);\n throw new Error(PAYMENT_CANNOT_CONTINUE);\n }\n });\n }\n\n private _createHiddenIframe(body: WorldpayAccessAdditionalAction): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n document.body.appendChild(iframe);\n\n if (!iframe.contentWindow) {\n throw new Error();\n }\n\n iframe.id = IFRAME_HIDDEN_NAME;\n iframe.height = '0px';\n iframe.width = '0px';\n\n const form = document.createElement('form');\n const formId = 'collectionForm';\n\n form.id = formId;\n form.name = 'devicedata';\n form.method = 'post';\n\n const url = body.additional_action_required.data.redirect_url;\n\n form.action = url;\n\n const inputBin = document.createElement('input');\n\n inputBin.name = 'Bin';\n inputBin.type = 'hidden';\n inputBin.value = body.provider_data.source_id;\n form.appendChild(inputBin);\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = body.provider_data.data;\n form.appendChild(inputJWT);\n\n const button = document.createElement('button');\n\n button.type = 'submit';\n button.id = 'btnsubmit';\n form.appendChild(button);\n\n if (navigator.userAgent.match('Firefox')) {\n iframe.srcdoc = form.outerHTML;\n } else {\n iframe.contentWindow.document.body.appendChild(form);\n }\n\n const script = document.createElement('script');\n\n script.innerHTML = `\n document.getElementById('${formId}').submit();\n `;\n iframe.contentWindow.document.body.appendChild(script);\n\n return iframe;\n }\n\n private _createIframe(data: WorldpayAccess3DSOptions): HTMLIFrameElement {\n const form = document.createElement('form');\n\n form.id = 'challengeForm';\n form.method = 'POST';\n form.action = data.acs_url;\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = data.payer_auth_request;\n form.appendChild(inputJWT);\n\n const merchant = document.createElement('input');\n\n merchant.name = 'MD';\n merchant.type = 'hidden';\n merchant.value = `merchantSessionId=${data.merchant_data}`;\n form.appendChild(merchant);\n\n const script = document.createElement('script');\n\n script.type = 'text/javascript';\n script.innerHTML =\n \"window.onload = function() { document.getElementById('challengeForm').submit(); }\";\n\n const iframe = document.createElement('iframe');\n\n iframe.name = IFRAME_NAME;\n iframe.height = '400';\n iframe.width = '100%';\n iframe.srcdoc = `${form.outerHTML} ${script.outerHTML}`;\n\n return iframe;\n }\n\n private _submitAdditionalAction() {\n if (this._shouldRenderHostedForm) {\n if (!this._hostedForm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const hostedForm = this._hostedForm;\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await hostedForm.submit(paymentPayload);\n };\n }\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await this._paymentIntegrationService.submitPayment(paymentPayload);\n };\n }\n\n private _isValidJsonWithSessionId(str: string) {\n try {\n const data = JSON.parse(str);\n\n if (data.SessionId) {\n return true;\n }\n\n return false;\n } catch (e) {\n return false;\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport WorldpayAccessPaymetStrategy from './worldpayaccess-payment-strategy';\n\nconst createWorldpayAccessPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new WorldpayAccessPaymetStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createWorldpayAccessPaymentStrategy, [{ id: 'worldpayaccess' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class StorefrontPaymentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async saveExternalId(methodId: string, token: string): Promise {\n const url = `/api/storefront/payment/${methodId}/save-external-id`;\n const options = {\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n externalId: token,\n provider: methodId,\n },\n };\n\n await this._requestSender.post(url, options);\n }\n}\n","import {\n isRequestError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n StorefrontPaymentRequestSender,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class ZipPaymentStrategy implements PaymentStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const { getPaymentMethodOrThrow } = await this.paymentIntegrationService.loadPaymentMethod(\n methodId,\n options,\n );\n\n const {\n clientToken,\n initializationData,\n }: { clientToken?: string; initializationData?: { redirectUrl?: string } } =\n getPaymentMethodOrThrow(methodId);\n const redirectUrl = initializationData?.redirectUrl;\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this.paymentIntegrationService\n .getState()\n .getCheckoutOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(useStoreCredit);\n await this.paymentIntegrationService.initializePayment(methodId, { useStoreCredit });\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n await this.paymentIntegrationService.submitPayment({\n methodId,\n paymentData: { nonce },\n });\n } catch (error) {\n if (isRequestError(error) && error.body.status === 'additional_action_required') {\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this.storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n StorefrontPaymentRequestSender,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ZipPaymentStrategy from './zip-payment-strategy';\n\nconst createZipPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n const requestSender = createRequestSender({ host: getHost() });\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n return new ZipPaymentStrategy(paymentIntegrationService, storefrontPaymentRequestSender);\n};\n\nexport default toResolvableModule(createZipPaymentStrategy, [{ id: 'zip' }, { id: 'quadpay' }]);\n","import { Action } from '@bigcommerce/data-store';\n\nimport Country from './country';\n\nexport enum CountryActionType {\n LoadCountriesRequested = 'LOAD_COUNTRIES_REQUESTED',\n LoadCountriesSucceeded = 'LOAD_COUNTRIES_SUCCEEDED',\n LoadCountriesFailed = 'LOAD_COUNTRIES_FAILED',\n}\n\nexport type LoadCountriesAction =\n | LoadCountriesRequestedAction\n | LoadCountriesSucceededAction\n | LoadCountriesFailedAction;\n\nexport interface LoadCountriesRequestedAction extends Action {\n type: CountryActionType.LoadCountriesRequested;\n}\n\nexport interface LoadCountriesSucceededAction extends Action {\n type: CountryActionType.LoadCountriesSucceeded;\n}\n\nexport interface LoadCountriesFailedAction extends Action {\n type: CountryActionType.LoadCountriesFailed;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Country from './country';\nimport { CountryActionType } from './country-actions';\nimport CountryRequestSender from './country-request-sender';\n\nexport default class CountryActionCreator {\n constructor(private _countryRequestSender: CountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable> {\n return Observable.create((observer: Observer>) => {\n observer.next(createAction(CountryActionType.LoadCountriesRequested));\n\n this._countryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(CountryActionType.LoadCountriesSucceeded, response.body.data),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CountryActionType.LoadCountriesFailed, response),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { CountryResponseBody } from './country-responses';\n\nexport default class CountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/store/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n PaymentStrategy,\n PaymentStrategyFactory,\n PaymentStrategyResolveId,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories = defaultPaymentStrategyFactories,\n options: { useFallback: boolean } = { useFallback: false },\n): ResolveIdRegistry {\n const { useFallback } = options;\n const registry = new ResolveIdRegistry(useFallback);\n\n for (const [, createPaymentStrategy] of Object.entries(paymentStrategyFactories)) {\n if (\n !isResolvableModule, PaymentStrategyResolveId>(\n createPaymentStrategy,\n )\n ) {\n continue;\n }\n\n for (const resolverId of createPaymentStrategy.resolveIds) {\n registry.register(resolverId, () => createPaymentStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","enum PaymentStrategyType {\n ADYENV2 = 'adyenv2',\n ADYENV2_GOOGLEPAY = 'googlepayadyenv2',\n ADYENV3 = 'adyenv3',\n ADYENV3_GOOGLEPAY = 'googlepayadyenv3',\n AFFIRM = 'affirm',\n AFTERPAY = 'afterpay',\n AUTHORIZENET_GOOGLE_PAY = 'googlepayauthorizenet',\n AMAZONPAY = 'amazonpay',\n APPLEPAY = 'applepay',\n BARCLAYS = 'barclays',\n BLUESNAPV2 = 'bluesnapv2',\n BOLT = 'bolt',\n CBA_MPGS = 'cba_mpgs',\n CHECKOUTCOM = 'checkoutcom',\n CHECKOUTCOM_APM = 'checkoutcomapm',\n CHECKOUTCOM_FAWRY = 'checkoutcomfawry',\n CHECKOUTCOM_SEPA = 'checkoutcomsepa',\n CHECKOUTCOM_IDEAL = 'checkoutcomideal',\n CREDIT_CARD = 'creditcard',\n CHECKOUTCOM_GOOGLE_PAY = 'googlepaycheckoutcom',\n CLEARPAY = 'clearpay',\n CONVERGE = 'converge',\n CYBERSOURCE = 'cybersource',\n CYBERSOURCEV2 = 'cybersourcev2',\n BNZ = 'bnz',\n BNZ_GOOGLEPAY = 'googlepaybnz',\n DIGITALRIVER = 'digitalriver',\n CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LAYBUY = 'laybuy',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\n OPY = 'opy',\n ORBITAL_GOOGLE_PAY = 'googlepayorbital',\n PAYPAL_EXPRESS = 'paypalexpress',\n PAYPAL_EXPRESS_CREDIT = 'paypalexpresscredit',\n PAYPAL_COMMERCE = 'paypalcommerce',\n PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit',\n PAYPAL_COMMERCE_CREDIT_CARD = 'paypalcommercecreditcards',\n PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods',\n PAYPAL_COMMERCE_VENMO = 'paypalcommercevenmo',\n PPSDK = 'PAYMENT_TYPE_SDK',\n QUADPAY = 'quadpay',\n SAGE_PAY = 'sagepay',\n SQUARE = 'squarev2',\n STRIPEV3 = 'stripev3',\n STRIPE_UPE = 'stripeupe',\n STRIPE_UPE_GOOGLE_PAY = 'googlepaystripeupe',\n BRAINTREE = 'braintree',\n BRAINTREE_PAYPAL = 'braintreepaypal',\n BRAINTREE_VENMO = 'braintreevenmo',\n BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n BRAINTREE_VISA_CHECKOUT = 'braintreevisacheckout',\n BRAINTREE_GOOGLE_PAY = 'googlepaybraintree',\n WE_PAY = 'wepay',\n WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n MASTERPASS = 'masterpass',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { PaymentStrategy as PaymentStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from './payment-request-options';\nimport {\n PaymentStrategyActionType,\n PaymentStrategyDeinitializeAction,\n PaymentStrategyExecuteAction,\n PaymentStrategyFinalizeAction,\n PaymentStrategyInitializeAction,\n PaymentStrategyWidgetAction,\n} from './payment-strategy-actions';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyRegistryV2 from './payment-strategy-registry-v2';\nimport PaymentStrategyType from './payment-strategy-type';\nimport PaymentStrategyWidgetActionCreator from './payment-strategy-widget-action-creator';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyActionCreator {\n private _paymentStrategyWidgetActionCreator: PaymentStrategyWidgetActionCreator;\n\n constructor(\n private _strategyRegistry: PaymentStrategyRegistry,\n private _strategyRegistryV2: PaymentStrategyRegistryV2,\n private _orderActionCreator: OrderActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {\n this._paymentStrategyWidgetActionCreator = new PaymentStrategyWidgetActionCreator();\n }\n\n execute(\n payload: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n const { payment = {} as OrderPaymentRequestBody, useStoreCredit } = payload;\n const meta = { methodId: payment.methodId };\n\n return (store) => {\n const { checkout } = store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n return concat(\n shouldExecuteSpamCheck\n ? this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(store)\n : empty(),\n of(createAction(PaymentStrategyActionType.ExecuteRequested, undefined, meta)),\n defer(() => {\n const state = store.getState();\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n if (state.payment.isPaymentDataRequired(useStoreCredit)) {\n const method = state.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n strategy = this._getStrategy(method);\n } else {\n strategy = this._strategyRegistryV2.get({\n id: PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED,\n });\n }\n\n const promise: Promise = strategy.execute(\n payload,\n {\n ...options,\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n },\n );\n\n return promise.then(() =>\n createAction(PaymentStrategyActionType.ExecuteSucceeded, undefined, meta),\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.ExecuteFailed, error, meta),\n ),\n );\n };\n }\n\n finalize(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentStrategyActionType.FinalizeRequested)),\n this._loadOrderPaymentsIfNeeded(store, options),\n defer(async () => {\n const state = store.getState();\n const { providerId = '', gatewayId = '' } = state.payment.getPaymentId() || {};\n const method = state.paymentMethods.getPaymentMethod(providerId, gatewayId);\n\n if (!method) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const strategy = this._getStrategy(method);\n\n await strategy.finalize({\n ...options,\n methodId: method.id,\n gatewayId: method.gateway,\n });\n\n return createAction(PaymentStrategyActionType.FinalizeSucceeded, undefined, {\n methodId: method.id,\n });\n }),\n ).pipe(\n catchError((error) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n\n return throwErrorAction(PaymentStrategyActionType.FinalizeFailed, error, {\n methodId: payment && payment.providerId,\n });\n }),\n );\n }\n\n initialize(\n options: PaymentInitializeOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.initialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.InitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.InitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.InitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n deinitialize(\n options: PaymentRequestOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && !state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.deinitialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.DeinitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.DeinitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n return this._paymentStrategyWidgetActionCreator.widgetInteraction(method, options);\n }\n\n private _getStrategy(method: PaymentMethod): PaymentStrategy | PaymentStrategyV2 {\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._strategyRegistry.getByMethod(method);\n } catch {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n }\n\n return strategy;\n }\n\n private _loadOrderPaymentsIfNeeded(\n store: ReadableCheckoutStore,\n options?: RequestOptions,\n ): Observable {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (checkout && checkout.orderId) {\n return this._orderActionCreator.loadOrderPayments(checkout.orderId, options);\n }\n\n return empty();\n }\n}\n","import { default as storage } from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private _namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = storage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n // Clean up invalid values\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return storage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return storage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this._namespace}.${key}`;\n }\n}\n","export const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","import PaymentMethod from './payment-method';\nimport PaymentStrategyType from './payment-strategy-type';\n\ntype PPSDKRequiredProperties = 'initializationStrategy';\n\nexport type PPSDKPaymentMethod = PaymentMethod & {\n type: PaymentStrategyType.PPSDK;\n} & Required>;\n\nexport const isPPSDKPaymentMethod = (\n paymentMethod: PaymentMethod,\n): paymentMethod is PPSDKPaymentMethod => {\n const { type, initializationStrategy } = paymentMethod;\n\n return type === PaymentStrategyType.PPSDK && typeof initializationStrategy?.type === 'string';\n};\n","import { InvalidArgumentError } from '../common/error/errors';\nimport { Registry, RegistryOptions } from '../common/registry';\n\nimport PaymentMethod from './payment-method';\nimport * as paymentMethodTypes from './payment-method-types';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { isPPSDKPaymentMethod } from './ppsdk-payment-method';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyRegistry extends Registry<\n PaymentStrategy,\n PaymentStrategyType\n> {\n getByMethod(paymentMethod?: PaymentMethod): PaymentStrategy {\n if (!paymentMethod) {\n return this.get();\n }\n\n const token = this._getToken(paymentMethod);\n\n const cacheToken = [paymentMethod.gateway, paymentMethod.id]\n .filter((value) => value !== undefined && value !== null)\n .join('-');\n\n return this.get(token, cacheToken);\n }\n\n private _getToken(paymentMethod: PaymentMethod): PaymentStrategyType {\n if (isPPSDKPaymentMethod(paymentMethod)) {\n return PaymentStrategyType.PPSDK;\n }\n\n if (paymentMethod.gateway === 'klarna') {\n return PaymentStrategyType.KLARNAV2;\n }\n\n const methodId = paymentMethod.gateway || paymentMethod.id;\n\n if (this._hasFactoryForMethod(methodId)) {\n return methodId;\n }\n\n if (paymentMethod.type === paymentMethodTypes.OFFLINE) {\n return PaymentStrategyType.OFFLINE;\n }\n\n throw new InvalidArgumentError(`'${methodId}' is not registered.`);\n }\n\n private _hasFactoryForMethod(methodId: string): methodId is PaymentStrategyType {\n return this._hasFactory(methodId);\n }\n}\n\nexport interface PaymentStrategyRegistryOptions extends RegistryOptions {\n clientSidePaymentProviders?: string[];\n}\n","import { InvalidArgumentError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import { isNil, values } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve(this._store.getState());\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._hostedFormFactory.create(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return this._store.getState();\n });\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n protected _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n protected _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return form\n .validate()\n .then(() => this._store.dispatch(this._orderActionCreator.submitOrder(order, options)))\n .then(() => form.submit(payment))\n .then(() => this._store.dispatch(this._orderActionCreator.loadCurrentOrder()));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(options?: PaymentInitializeOptions): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BarclaysPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BNZPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const { methodId } = payload.payment;\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { BraintreeError } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeFormErrorsData, BraintreeVerifyPayload } from './braintree';\n\n/**\n * A set of options that are required to initialize the Braintree payment\n * method. You need to provide the options if you want to support 3D Secure\n * authentication flow.\n *\n * ```html\n * \n *
\n *
\n *
\n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * braintree: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * },\n * },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * creditCard: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * styles: {\n * default: {\n * color: '#000',\n * },\n * error: {\n * color: '#f00',\n * },\n * focus: {\n * color: '#0f0',\n * },\n * },\n * onBlur({ fieldType }) {\n * console.log(fieldType);\n * },\n * onFocus({ fieldType }) {\n * console.log(fieldType);\n * },\n * onEnter({ fieldType }) {\n * console.log(fieldType);\n * },\n * onCardTypeChange({ cardType }) {\n * console.log(cardType);\n * },\n * onValidate({ errors, isValid }) {\n * console.log(errors);\n * console.log(isValid);\n * },\n * },\n * },\n * });\n * ```\n */\nexport interface BraintreePaymentInitializeOptions {\n /**\n * The CSS selector of a container where the payment widget should be inserted into.\n */\n containerId?: string;\n\n threeDSecure?: BraintreeThreeDSecureOptions;\n\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n form?: BraintreeFormOptions;\n\n /**\n * The location to insert the Pay Later Messages.\n */\n bannerContainerId?: string;\n\n /**\n * A callback right before render Smart Payment Button that gets called when\n * Smart Payment Button is eligible. This callback can be used to hide the standard submit button.\n */\n onRenderButton?(): void;\n\n /**\n * A callback for submitting payment form that gets called\n * when buyer approved PayPal account.\n */\n submitForm?(): void;\n\n /**\n * A callback that gets called if unable to submit payment.\n *\n * @param error - The error object describing the failure.\n */\n onPaymentError?(error: BraintreeError | StandardError): void;\n\n /**\n * A callback for displaying error popup. This callback requires error object as parameter.\n */\n onError?(error: unknown): void;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\nexport interface BraintreeThreeDSecureOptions {\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param error - Any error raised during the verification process;\n * undefined if there is none.\n * @param iframe - The iframe element containing the verification web page\n * provided by the card issuer.\n * @param cancel - A function, when called, will cancel the verification\n * process and remove the iframe.\n */\n addFrame(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n\n /**\n * A callback that gets called when the iframe is about to be removed from\n * the current page.\n */\n removeFrame(): void;\n challengeRequested?: boolean;\n additionalInformation?: {\n acsWindowSize?: '01' | '02' | '03' | '04' | '05';\n };\n}\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return !!(fields as BraintreeFormFieldsMap).cardNumber;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n (fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification\n );\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return (error as BraintreeError).name === 'BraintreeError';\n}\n","import { BraintreeHostedFormError } from './braintree';\nimport isBraintreeError from './is-braintree-error';\n\nfunction isValidInvalidFieldKeys(invalidFieldKeys: any): invalidFieldKeys is string[] {\n return (\n Array.isArray(invalidFieldKeys) && invalidFieldKeys.every((key) => typeof key === 'string')\n );\n}\n\nexport function isBraintreeHostedFormError(error: any): error is BraintreeHostedFormError {\n if (!isBraintreeError(error)) {\n return false;\n }\n\n const { details } = error;\n\n return (\n details === undefined ||\n (typeof details === 'object' &&\n details !== null &&\n (details as { invalidFieldKeys?: unknown }).invalidFieldKeys === undefined) ||\n isValidInvalidFieldKeys((details as { invalidFieldKeys?: unknown }).invalidFieldKeys)\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails } from '../../errors';\n\nimport {\n BraintreeBillingAddressRequestData,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n TokenizationPayload,\n} from './braintree';\nimport {\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeStoredCardFieldsMap,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { isBraintreeFormFieldsMap } from './is-braintree-form-fields-map';\nimport { isBraintreeHostedFormError } from './is-braintree-hosted-form-error';\n\nenum BraintreeHostedFormType {\n CreditCard,\n StoredCardVerification,\n}\n\nexport default class BraintreeHostedForm {\n private _cardFields?: BraintreeHostedFields;\n private _formOptions?: BraintreeFormOptions;\n private _type?: BraintreeHostedFormType;\n private _isInitializedHostedForm = false;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n async initialize(options: BraintreeFormOptions): Promise {\n this._formOptions = options;\n\n this._type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this._mapFieldOptions(options.fields);\n\n if (isEmpty(fields)) {\n this._isInitializedHostedForm = false;\n\n return;\n }\n\n this._cardFields = await this._braintreeSDKCreator.createHostedFields({\n fields,\n styles: options.styles && this._mapStyleOptions(options.styles),\n });\n\n this._cardFields.on('blur', this._handleBlur);\n this._cardFields.on('focus', this._handleFocus);\n this._cardFields.on('cardTypeChange', this._handleCardTypeChange);\n this._cardFields.on('validityChange', this._handleValidityChange);\n this._cardFields.on('inputSubmitRequest', this._handleInputSubmitRequest);\n\n this._isInitializedHostedForm = true;\n }\n\n isInitialized(): boolean {\n return !!this._isInitializedHostedForm;\n }\n\n async deinitialize(): Promise {\n if (this._isInitializedHostedForm) {\n this._isInitializedHostedForm = false;\n\n await this._cardFields?.teardown();\n }\n }\n\n validate() {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const braintreeHostedFormState = this._cardFields.getState();\n\n if (!this._isValidForm(braintreeHostedFormState)) {\n this._handleValidityChange(braintreeHostedFormState);\n\n const errors = this._mapValidationErrors(braintreeHostedFormState.fields);\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n async tokenize(billingAddress: Address): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const tokenizationPayload = await this._cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this._mapBillingAddress(billingAddress),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return {\n nonce: tokenizationPayload.nonce,\n bin: tokenizationPayload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this._mapTokenizeError(error);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n async tokenizeForStoredCardVerification(): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const tokenizationPayload = await this._cardFields.tokenize();\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return {\n nonce: tokenizationPayload.nonce,\n bin: tokenizationPayload.details?.bin,\n };\n } catch (error) {\n if (isBraintreeHostedFormError(error)) {\n const errors = this._mapTokenizeError(error, true);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n }\n\n throw error;\n }\n }\n\n private _mapBillingAddress(billingAddress: Address): BraintreeBillingAddressRequestData {\n return {\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n };\n }\n\n private _mapFieldOptions(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n },\n expirationDate: {\n container: `#${fields.cardExpiry.containerId}`,\n placeholder: fields.cardExpiry.placeholder,\n internalLabel: fields.cardExpiry.accessibilityLabel,\n },\n cvv: fields.cardCode && {\n container: `#${fields.cardCode.containerId}`,\n placeholder: fields.cardCode.placeholder,\n internalLabel: fields.cardCode.accessibilityLabel,\n },\n cardholderName: {\n container: `#${fields.cardName.containerId}`,\n placeholder: fields.cardName.placeholder,\n internalLabel: fields.cardName.accessibilityLabel,\n },\n },\n isNil,\n );\n }\n\n return omitBy(\n {\n number: fields.cardNumberVerification && {\n container: `#${fields.cardNumberVerification.containerId}`,\n placeholder: fields.cardNumberVerification.placeholder,\n },\n cvv: fields.cardCodeVerification && {\n container: `#${fields.cardCodeVerification.containerId}`,\n placeholder: fields.cardCodeVerification.placeholder,\n },\n },\n isNil,\n );\n }\n\n private _mapStyleOptions(\n options: BraintreeFormFieldStylesMap,\n ): BraintreeHostedFieldsCreatorConfig['styles'] {\n const mapStyles = (styles: BraintreeFormFieldStyles = {}) =>\n omitBy(\n {\n color: styles.color,\n 'font-family': styles.fontFamily,\n 'font-size': styles.fontSize,\n 'font-weight': styles.fontWeight,\n },\n isNil,\n ) as Dictionary;\n\n return {\n input: mapStyles(options.default),\n '.invalid': mapStyles(options.error),\n ':focus': mapStyles(options.focus),\n };\n }\n\n private _mapFieldType(type: string): BraintreeFormFieldType {\n switch (type) {\n case 'number':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardNumberVerification\n : BraintreeFormFieldType.CardNumber;\n\n case 'expirationDate':\n return BraintreeFormFieldType.CardExpiry;\n\n case 'cvv':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardCodeVerification\n : BraintreeFormFieldType.CardCode;\n\n case 'cardholderName':\n return BraintreeFormFieldType.CardName;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private _mapErrors(fields: BraintreeHostedFieldsState['fields']): BraintreeFormErrorsData {\n const errors: BraintreeFormErrorsData = {};\n\n if (fields) {\n for (const [key, value] of Object.entries(fields)) {\n if (value && this._isValidParam(key)) {\n const { isValid, isEmpty, isPotentiallyValid } = value;\n\n errors[key] = {\n isValid,\n isEmpty,\n isPotentiallyValid,\n };\n }\n }\n }\n\n return errors;\n }\n\n private _mapValidationErrors(\n fields: BraintreeHostedFieldsState['fields'],\n ): BraintreeFormFieldValidateEventData['errors'] {\n return (Object.keys(fields) as Array).reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid\n ? undefined\n : [this._createInvalidError(this._mapFieldType(fieldKey))],\n }),\n {},\n );\n }\n\n private _mapTokenizeError(\n error: BraintreeHostedFormError,\n isStoredCard = false,\n ): BraintreeFormFieldValidateEventData['errors'] | undefined {\n if (error.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {\n const cvvValidation = {\n [this._mapFieldType('cvv')]: [this._createRequiredError(this._mapFieldType('cvv'))],\n };\n\n const expirationDateValidation = {\n [this._mapFieldType('expirationDate')]: [\n this._createRequiredError(this._mapFieldType('expirationDate')),\n ],\n };\n\n const cardNumberValidation = {\n [this._mapFieldType('number')]: [\n this._createRequiredError(this._mapFieldType('number')),\n ],\n };\n\n const cardNameValidation = {\n [this._mapFieldType('cardholderName')]: [\n this._createRequiredError(this._mapFieldType('cardholderName')),\n ],\n };\n\n return isStoredCard\n ? cvvValidation\n : {\n ...cvvValidation,\n ...expirationDateValidation,\n ...cardNumberValidation,\n ...cardNameValidation,\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: [\n this._createInvalidError(this._mapFieldType(fieldKey)),\n ],\n }),\n {},\n );\n }\n\n private _createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'CVV is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Credit card number is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Expiration date is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Full name is required',\n type: 'required',\n };\n\n default:\n return {\n fieldType,\n message: 'Field is required',\n type: 'required',\n };\n }\n }\n\n private _createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Invalid card name',\n type: 'invalid_card_name',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private _handleBlur: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onBlur?.({\n fieldType: this._mapFieldType(event.emittedBy),\n errors: this._mapErrors(event.fields),\n });\n };\n\n private _handleFocus: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onFocus?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleCardTypeChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onCardTypeChange?.({\n cardType:\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master\\-card$/, 'mastercard',) /* eslint-disable-line */\n : undefined,\n });\n };\n\n private _handleInputSubmitRequest: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onEnter?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleValidityChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onValidate?.({\n isValid: this._isValidForm(event),\n errors: this._mapValidationErrors(event.fields),\n });\n };\n\n private _isValidForm(event: BraintreeHostedFieldsState): boolean {\n return (\n Object.keys(event.fields) as Array\n ).every((key) => event.fields[key]?.isValid);\n }\n\n private _isValidParam(\n formErrorDataKey: string,\n ): formErrorDataKey is BraintreeFormErrorDataKeys {\n switch (formErrorDataKey) {\n case 'number':\n case 'cvv':\n case 'expirationDate':\n case 'postalCode':\n case 'cardholderName':\n case 'cardType':\n return true;\n\n default:\n return false;\n }\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","import { isEmpty } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderPaymentRequestBody } from '../../../order';\nimport {\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n} from '../../errors';\nimport { CreditCardInstrument, NonceInstrument } from '../../payment';\n\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeRequestData,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVerifyPayload,\n TokenizationPayload,\n} from './braintree';\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport {\n BraintreeFormOptions,\n BraintreePaymentInitializeOptions,\n BraintreeThreeDSecureOptions,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport isCreditCardInstrumentLike from './is-credit-card-instrument-like';\n\nexport default class BraintreePaymentProcessor {\n private _threeDSecureOptions?: BraintreeThreeDSecureOptions;\n\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _braintreeHostedForm: BraintreeHostedForm,\n ) {}\n\n initialize(clientToken: string, options?: BraintreePaymentInitializeOptions): void {\n this._braintreeSDKCreator.initialize(clientToken);\n this._threeDSecureOptions = options?.threeDSecure;\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n preloadPaypalCheckout(\n paypalCheckoutConfig: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ) {\n return this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutConfig,\n onSuccess,\n onError,\n );\n }\n\n async tokenizeCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n ): Promise {\n const { paymentData } = payment;\n\n if (!isCreditCardInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const errors = this._getErrorsRequiredFields(paymentData);\n\n if (!isEmpty(errors)) {\n throw new PaymentInvalidFormError(errors);\n }\n\n const requestData = this._mapToCreditCard(paymentData, billingAddress);\n const client = await this._braintreeSDKCreator.getClient();\n const { creditCards } = await client.request(requestData);\n\n return {\n nonce: creditCards[0].nonce,\n bin: creditCards[0].details?.bin,\n };\n }\n\n async verifyCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n amount: number,\n ): Promise {\n const tokenizationPayload = await this.tokenizeCard(payment, billingAddress);\n\n return this.challenge3DSVerification(tokenizationPayload, amount);\n }\n\n getSessionId(): Promise {\n return this._braintreeSDKCreator.getDataCollector().then(({ deviceData }) => deviceData);\n }\n\n /**\n * @deprecated Use getSessionId() and combine them in the consumer.\n */\n appendSessionId(processedPayment: Promise): Promise {\n return processedPayment\n .then((paymentData) =>\n Promise.all([paymentData, this._braintreeSDKCreator.getDataCollector()]),\n )\n .then(([paymentData, { deviceData }]) => ({\n ...paymentData,\n deviceSessionId: deviceData,\n }));\n }\n\n async initializeHostedForm(options: BraintreeFormOptions): Promise {\n return this._braintreeHostedForm.initialize(options);\n }\n\n validateHostedForm() {\n return this._braintreeHostedForm.validate();\n }\n\n isInitializedHostedForm(): boolean {\n return this._braintreeHostedForm.isInitialized();\n }\n\n async deinitializeHostedForm(): Promise {\n await this._braintreeHostedForm.deinitialize();\n }\n\n tokenizeHostedForm(billingAddress: Address): Promise {\n return this._braintreeHostedForm.tokenize(billingAddress);\n }\n\n tokenizeHostedFormForStoredCardVerification(): Promise {\n return this._braintreeHostedForm.tokenizeForStoredCardVerification();\n }\n\n async verifyCardWithHostedForm(\n billingAddress: Address,\n amount: number,\n ): Promise {\n const tokenizationPayload = await this._braintreeHostedForm.tokenize(billingAddress);\n\n return this.challenge3DSVerification(tokenizationPayload, amount);\n }\n\n async challenge3DSVerification(\n tokenizationPayload: TokenizationPayload,\n amount: number,\n ): Promise {\n const threeDSecure = await this._braintreeSDKCreator.get3DS();\n\n return this._present3DSChallenge(threeDSecure, amount, tokenizationPayload);\n }\n\n async getVenmoCheckout(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeSDKCreator.getVenmoCheckout(resolve, reject);\n });\n }\n\n private _getErrorsRequiredFields(\n paymentData: CreditCardInstrument,\n ): PaymentInvalidFormErrorDetails {\n const { ccNumber, ccExpiry } = paymentData;\n const errors: PaymentInvalidFormErrorDetails = {};\n\n if (!ccNumber) {\n errors.ccNumber = [\n {\n message: 'Credit card number is required',\n type: 'required',\n },\n ];\n }\n\n if (!ccExpiry) {\n errors.ccExpiry = [\n {\n message: 'Expiration date is required',\n type: 'required',\n },\n ];\n }\n\n return errors;\n }\n\n private _present3DSChallenge(\n threeDSecure: BraintreeThreeDSecure,\n amount: number,\n tokenizationPayload: TokenizationPayload,\n ): Promise {\n const { nonce, bin } = tokenizationPayload;\n\n if (!this._threeDSecureOptions || !nonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n addFrame,\n removeFrame,\n challengeRequested = true,\n additionalInformation,\n } = this._threeDSecureOptions;\n const cancelVerifyCard = async () => {\n const response = await threeDSecure.cancelVerifyCard();\n\n verification.cancel(new PaymentMethodCancelledError());\n\n return response;\n };\n\n const roundedAmount = amount.toFixed(2);\n\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n addFrame: (error, iframe) => {\n addFrame(error, iframe, cancelVerifyCard);\n },\n amount: Number(roundedAmount),\n bin,\n challengeRequested,\n nonce,\n removeFrame,\n onLookupComplete: (_data, next) => {\n next();\n },\n collectDeviceData: true,\n additionalInformation,\n }),\n );\n\n return verification.promise;\n }\n\n private _mapToCreditCard(\n creditCard: CreditCardInstrument,\n billingAddress?: Address,\n ): BraintreeRequestData {\n return {\n data: {\n creditCard: {\n cardholderName: creditCard.ccName,\n number: creditCard.ccNumber,\n cvv: creditCard.ccCvv,\n expirationDate: `${creditCard.ccExpiry.month}/${creditCard.ccExpiry.year}`,\n options: {\n validate: false,\n },\n billingAddress: billingAddress && {\n countryCodeAlpha2: billingAddress.countryCode,\n locality: billingAddress.city,\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n },\n },\n },\n endpoint: 'payment_methods/credit_cards',\n method: 'post',\n };\n }\n}\n","import { CreditCardInstrument } from '../../payment';\n\nexport default function isCreditCardInstrumentLike(\n instrument: any,\n): instrument is CreditCardInstrument {\n return (\n instrument &&\n typeof instrument.ccExpiry === 'object' &&\n typeof instrument.ccNumber === 'string' &&\n typeof instrument.ccName === 'string'\n );\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport {\n BraintreeIntegrationService,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { isHostedInstrumentLike, PaymentMethod } from '../../index';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { PaymentInstrument, PaymentInstrumentMeta } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreePaymentProcessor from './braintree-payment-processor';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private _is3dsEnabled?: boolean;\n private _isHostedFormInitialized?: boolean;\n private _deviceSessionId?: string;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n private _braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, gatewayId, braintree } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const { clientToken } = this._paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken, braintree);\n\n if (this._isHostedPaymentFormEnabled(methodId, gatewayId) && braintree?.form) {\n await this._braintreePaymentProcessor.initializeHostedForm(braintree.form);\n this._isHostedFormInitialized =\n this._braintreePaymentProcessor.isInitializedHostedForm();\n }\n\n this._is3dsEnabled = this._paymentMethod.config.is3dsEnabled;\n this._deviceSessionId = await this._braintreePaymentProcessor.getSessionId();\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n if (this._shouldInitializeBraintreeFastlane()) {\n await this._initializeBraintreeFastlaneOrThrow(methodId);\n }\n } catch (error) {\n return this._handleError(error);\n }\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (this._isHostedFormInitialized) {\n this._braintreePaymentProcessor.validateHostedForm();\n }\n\n const {\n billingAddress: { getBillingAddressOrThrow },\n order: { getOrderOrThrow },\n } = await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const billingAddress = getBillingAddressOrThrow();\n const orderAmount = getOrderOrThrow().orderAmount;\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: this._isHostedFormInitialized\n ? await this._prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this._preparePaymentData(payment, billingAddress, orderAmount),\n }),\n );\n } catch (error) {\n return this._processAdditionalAction(error, payment, orderAmount);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this._isHostedFormInitialized = false;\n\n await Promise.all([\n this._braintreePaymentProcessor.deinitialize(),\n this._braintreePaymentProcessor.deinitializeHostedForm(),\n ]);\n\n return this._store.getState();\n }\n\n private _handleError(error: unknown): never {\n if (error instanceof Error && error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n return {\n ...commonPaymentData,\n ...paymentData,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCard(payment, billingAddress, orderAmount)\n : await this._braintreePaymentProcessor.tokenizeCard(payment, billingAddress);\n\n return {\n ...commonPaymentData,\n nonce,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n private async _prepareHostedPaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n const { nonce } =\n await this._braintreePaymentProcessor.tokenizeHostedFormForStoredCardVerification();\n\n return {\n ...commonPaymentData,\n ...paymentData,\n nonce,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCardWithHostedForm(\n billingAddress,\n orderAmount,\n )\n : await this._braintreePaymentProcessor.tokenizeHostedForm(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this._handleError(error);\n }\n\n try {\n const {\n instruments: { getCardInstrumentOrThrow },\n } = this._store.getState();\n const { payer_auth_request: storedCreditCardNonce } = error.body.three_ds_result || {};\n const { paymentData } = payment;\n\n if (!paymentData || !isVaultedInstrument(paymentData)) {\n throw new PaymentArgumentInvalidError(['instrumentId']);\n }\n\n const instrument = getCardInstrumentOrThrow(paymentData.instrumentId);\n const { nonce } = await this._braintreePaymentProcessor.challenge3DSVerification(\n {\n nonce: storedCreditCardNonce,\n bin: instrument.iin,\n },\n orderAmount,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n deviceSessionId: this._deviceSessionId,\n nonce,\n },\n }),\n );\n } catch (error) {\n return this._handleError(error);\n }\n }\n\n private _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isSubmittingWithStoredCard(payment: OrderPaymentRequestBody): boolean {\n return !!(payment.paymentData && isVaultedInstrument(payment.paymentData));\n }\n\n private _shouldPerform3DSVerification(payment: OrderPaymentRequestBody): boolean {\n return !!(this._is3dsEnabled && !this._isSubmittingWithStoredCard(payment));\n }\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n private _shouldInitializeBraintreeFastlane() {\n const state = this._store.getState();\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n const isAcceleratedCheckoutEnabled =\n this._paymentMethod?.initializationData.isAcceleratedCheckoutEnabled;\n\n return (\n isAcceleratedCheckoutEnabled && !braintreePaymentProviderCustomer?.authenticationState\n );\n }\n\n // TODO: remove this part when BT AXO A/B testing will be finished\n private async _initializeBraintreeFastlaneOrThrow(methodId: string): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeIntegrationService.initialize(clientToken);\n\n await this._braintreeIntegrationService.getBraintreeFastlane(cart.id, config.testMode);\n }\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError, BraintreeTokenizePayload, BraintreeVenmoCheckout } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private _braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._initializeBraintreeVenmo(paymentMethod);\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this._preparePaymentData(payment);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentData),\n );\n } catch (error) {\n this._handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._braintreePaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n private _handleError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _initializeBraintreeVenmo(paymentMethod: PaymentMethod): Promise {\n const { clientToken } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken);\n this._braintreeVenmoCheckout = await this._braintreePaymentProcessor.getVenmoCheckout();\n } catch (error) {\n this._handleError(error);\n }\n }\n\n private async _preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const { nonce } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this._formattedPayload(nonce) };\n }\n\n const tokenizeResult = await this._braintreeVenmoTokenize();\n const sessionId = await this._braintreePaymentProcessor.getSessionId();\n\n return {\n ...payment,\n paymentData: this._formattedPayload(\n tokenizeResult.nonce,\n tokenizeResult.details.email,\n sessionId,\n ),\n };\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _braintreeVenmoTokenize(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeVenmoCheckout?.tokenize(\n (error: BraintreeError | undefined, payload: BraintreeTokenizePayload) => {\n if (error) {\n return reject(error);\n }\n\n resolve(payload);\n },\n );\n });\n }\n}\n","import { noop } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\nimport { VisaCheckoutPaymentSuccessPayload } from './visacheckout';\nimport VisaCheckoutScriptLoader from './visacheckout-script-loader';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { clientToken, config } = this._paymentMethod || {};\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onError = noop, onPaymentSelect = noop } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: false,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(config?.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n clientToken,\n initOptions,\n ),\n ]).then(([visaCheckout, visaInitOptions]) => {\n visaCheckout.init(visaInitOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload)\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n });\n })\n .then(() => this._store.getState());\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.nonce\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this._paymentMethod.initializationData;\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: { nonce },\n }),\n ),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(() =>\n Promise.all([\n this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n ),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n ),\n ]),\n );\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { InstrumentSelector } from '../../instrument';\nimport isCreditCardLike from '../../is-credit-card-like';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (error) {\n if (\n error instanceof RequestError &&\n some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = error.body.three_ds_result;\n const token = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return await this._submitPayment(payment, { token }, hostedForm);\n }\n\n throw error;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._store.getState();\n const billingAddress = store.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = store.shippingAddress.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.checkout.getCheckoutOrThrow();\n const id = store.order.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: InstrumentSelector['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardLike(paymentData) && paymentData.ccNumber;\n const bin = instrument ? instrument.iin : hostedForm ? hostedForm.getBin() : ccNumber;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument, PaymentInstrument } from './payment';\n\nexport default function isCreditCardLike(\n instrument: PaymentInstrument,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '../../payment';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted](setupCompleteData: CardinalSetupCompletedData): void;\n [CardinalEventType.Validated](data: CardinalValidatedData, jwt?: string): void;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { CreditCardInstrument, ThreeDSecureToken, VaultedInstrument } from '../../payment';\nimport { ThreeDsResult } from '../../payment-response-body';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(() => {});\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(() => {}),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if a payment method explicitly returns a declined error and\n * the shopper has to choose a different payment method if they wish to continue\n * their checkout process.\n */\nexport default class PaymentMethodDeclinedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'The selected payment method was declined. Please select another payment method.',\n );\n\n this.name = 'PaymentMethodDeclinedError';\n this.type = 'payment_declined';\n }\n}\n","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\n","import { noop, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodDeclinedError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n RestApiResponse,\n THREE_D_SECURE_AVAILABLE,\n THREE_D_SECURE_BUSY,\n THREE_D_SECURE_PROCEED,\n ThreeDSjs,\n} from './cba-mpgs';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private _threeDSjs?: ThreeDSjs;\n private _sessionId = '';\n\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _CBAMGPSScriptLoader: CBAMPGSScriptLoader,\n private _locale: string,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n clientToken,\n initializationData: { isTestModeFlagEnabled = false, merchantId },\n config: { is3dsEnabled },\n } = paymentMethod;\n\n if (is3dsEnabled) {\n this._threeDSjs = await this._CBAMGPSScriptLoader.load(isTestModeFlagEnabled);\n\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!clientToken || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._sessionId = clientToken;\n\n await this._threeDSjs.configure({\n merchantId,\n sessionId: this._sessionId,\n callback: () => {\n if (this._threeDSjs?.isConfigured()) {\n return this._store.getState();\n }\n\n throw new PaymentMethodFailedError('Failed to configure 3DS API.');\n },\n configuration: {\n userLanguage: this._locale,\n wsVersion: 62,\n },\n });\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const { is3dsEnabled } = paymentMethod.config;\n\n if (is3dsEnabled) {\n const newPaymentData = {\n ...paymentData,\n threeDSecure: { token: this._sessionId },\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error) => {\n if (\n !is3dsEnabled ||\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const state = this._store.getState();\n const order = state.order.getOrder();\n const {\n storeProfile: { storeId },\n } = state.config.getStoreConfigOrThrow();\n\n if (!order || !this._sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n const {\n three_ds_result: { token: transactionId },\n } = error.body;\n\n if (!transactionId) {\n return Promise.reject(error);\n }\n\n return this._initiateAuthentication(orderId, transactionId);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._threeDSjs = undefined;\n this._sessionId = '';\n\n return super.deinitialize();\n }\n\n private async _initiateAuthentication(\n orderId: string,\n transactionId: string,\n ): Promise {\n const response: RestApiResponse = await new Promise((resolve, reject) => {\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._threeDSjs.initiateAuthentication(orderId, transactionId, (data) => {\n const error = data.error;\n\n if (error) {\n return reject(new PaymentMethodDeclinedError(error.msg));\n }\n\n if (this._threeDSjs && data.gatewayRecommendation === THREE_D_SECURE_PROCEED) {\n return resolve(data.restApiResponse);\n }\n\n return reject(new PaymentMethodDeclinedError());\n });\n });\n\n if (\n response.transaction &&\n response.transaction.authenticationStatus === THREE_D_SECURE_AVAILABLE\n ) {\n return this._authenticatePayer(orderId, transactionId);\n }\n\n throw new PaymentMethodDeclinedError();\n }\n\n private async _authenticatePayer(\n orderId: string,\n transactionId: string,\n attempt = 1,\n ): Promise {\n return new Promise((_resolve, reject) => {\n if (!this._threeDSjs) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this._threeDSjs.authenticatePayer(\n orderId,\n transactionId,\n async (data) => {\n const error = data.error;\n\n if (error) {\n if (error.cause && error.cause === THREE_D_SECURE_BUSY && attempt < 5) {\n // Wait 3 seconds for MPGS server to process the `initiateAuthentication` call\n // See: Step 1: Initiate Authentication -> Initiate Authentication Request:\n // https://ap-gateway.mastercard.com/api/documentation/integrationGuidelines/supportedFeatures/pickAdditionalFunctionality/authentication/3DS/integrationModelAPI.html?locale=en_US#x_3DSTest\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n return this._authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodDeclinedError());\n }\n\n // ThreeDSjs will handle the redirect so return a promise that doesn't really resolve\n return new Promise(noop);\n },\n { fullScreenRedirect: true },\n );\n });\n }\n}\n","export const THREE_D_SECURE_PROCEED = 'PROCEED';\nexport const THREE_D_SECURE_BUSY = 'SERVER_BUSY';\nexport const THREE_D_SECURE_AVAILABLE = 'AUTHENTICATION_AVAILABLE';\n\nexport interface CBAMPGSHostWindow extends Window {\n ThreeDS?: ThreeDSjs;\n}\n\nexport interface ThreeDSjs {\n // Configuration method for initializing the API.\n configure(config: ThreeDSConfiguration): Promise;\n // Convenience method to check if the API has been configured successfully.\n isConfigured(): boolean;\n // Authentication for the arguments passed.\n initiateAuthentication(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n ): void;\n authenticatePayer(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n optionalParams?: AuthenticatePayerOptionalParams,\n ): void;\n}\n\nexport interface RestApiResponse {\n transaction: {\n authenticationStatus: string;\n };\n}\n\n// Configuration required to configure ThreeDS\nexport interface ThreeDSConfiguration {\n merchantId: string;\n sessionId: string;\n configuration: ThreeDSAPIConfiguration;\n callback(): void;\n}\n\nexport interface ThreeDSAuthenticationResponse {\n error?: ThreeDSAuthenticationError;\n restApiResponse: RestApiResponse;\n gatewayRecommendation: string;\n}\n\nexport interface AuthenticatePayerOptionalParams {\n fullScreenRedirect: boolean;\n}\n\nexport interface ThreeDSAuthenticationError {\n code: string;\n msg: string;\n cause?: string;\n}\n\n// JSON value supporting data elements like userLanguage, REST API version (wsVersion)\nexport interface ThreeDSAPIConfiguration {\n // A language identifier or IETF language tag to control the language of the payment page displayed to the payer.\n // For example, \"en_US\", es, \"fr-CA\". By default, the language is \"en_US\".\n userLanguage: string;\n // The Web Services API version that you submitted the request in. IE: 62\n wsVersion: number;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CBAMPGSHostWindow, ThreeDSjs } from './cba-mpgs';\n\nexport default class CBAMPGSScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CBAMPGSHostWindow = window) {}\n\n async load(testMode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n `//${\n testMode ? 'test' : 'ap'\n }-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`,\n );\n\n if (!this._window.ThreeDS) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.ThreeDS;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class ConvergePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return super.execute(payload, options).catch((error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n });\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport getCallbackUrl from './get-callback-url';\nimport { Masterpass, MasterpassCheckoutOptions } from './masterpass';\nimport MasterpassScriptLoader from './masterpass-script-loader';\n\nexport default class MasterpassPaymentStrategy implements PaymentStrategy {\n private _masterpassClient?: Masterpass;\n private _paymentMethod?: PaymentMethod;\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n\n if (!options.masterpass) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.masterpass\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.masterpass.walletButton &&\n document.getElementById(options.masterpass.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._store.getState();\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._masterpassClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const order = { useStoreCredit: payload.useStoreCredit };\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.gateway\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n // TODO: Refactor the API endpoint to return nonce in the right place.\n const paymentData = this._paymentMethod.initializationData.paymentData;\n\n // TODO: Redirect to Masterpass if nonce has not been generated yet. And then finalise the order when the shopper is redirected back to the checkout page.\n if (!paymentData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"paymentMethod.initializationData.paymentData\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.subtotal.toFixed(2),\n currency: storeConfig.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('checkout'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._masterpassClient) {\n return;\n }\n\n const payload = this._createMasterpassPayload();\n\n this._masterpassClient.checkout(payload);\n }\n}\n","import PaymentMethod from '../../payment-method';\n\nimport { OpyWidgetConfig } from './opy-library';\n\nexport enum ActionTypes {\n FORM_POST = 'FormPost',\n WAIT_FOR_CUSTOMER = 'WaitForCustomer',\n}\n\ninterface FormPost {\n type: ActionTypes.FORM_POST;\n formPost: {\n formPostUrl: string;\n formFields: [\n {\n fieldName: string;\n fieldValue: string;\n },\n ];\n };\n}\n\ninterface WaitForCustomer {\n type: ActionTypes.WAIT_FOR_CUSTOMER;\n}\n\nexport interface OpyPaymentMethod extends PaymentMethod {\n initializationData: {\n nextAction?: FormPost | WaitForCustomer;\n widgetConfig: OpyWidgetConfig;\n };\n}\n\nexport function isOpyPaymentMethod(\n paymentMethod: PaymentMethod,\n): paymentMethod is OpyPaymentMethod {\n return !!paymentMethod.initializationData?.widgetConfig;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum OpyErrorType {\n InvalidCart = 'invalid_cart',\n}\nexport default class OpyError extends StandardError {\n subtype: string;\n\n constructor(subtype: OpyErrorType, displayName: string) {\n super(getErrorMessage(subtype, displayName));\n\n this.name = 'OpyError';\n this.type = 'opy_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: OpyErrorType, displayName: string): string {\n switch (type) {\n case OpyErrorType.InvalidCart:\n return `Cart price is different to ${displayName} plan amount.`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { StorefrontPaymentRequestSender } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { ActionTypes, isOpyPaymentMethod } from './opy';\nimport { OpyWidgetConfig } from './opy-library';\nimport OpyError, { OpyErrorType } from './opy-payment-error';\nimport OpyScriptLoader from './opy-script-loader';\n\nexport default class OpyPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: OpyScriptLoader,\n ) {}\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (options?.opy?.containerId) {\n const {\n methodId,\n opy: { containerId },\n } = options;\n\n const paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod && isOpyPaymentMethod(paymentMethod)) {\n const {\n initializationData: { widgetConfig },\n } = paymentMethod;\n\n await this._installWidget(containerId, widgetConfig);\n }\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (!isOpyPaymentMethod(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken: nonce,\n initializationData: { nextAction },\n } = paymentMethod;\n\n if (!nextAction) {\n const { displayName = 'Openpay' } = paymentMethod.config;\n\n throw new OpyError(OpyErrorType.InvalidCart, displayName);\n }\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._storefrontPaymentRequestSender.saveExternalId(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (nextAction.type === ActionTypes.FORM_POST) {\n const { formPostUrl, formFields } = nextAction.formPost;\n\n const url = new URL(formPostUrl.replace(/\\/$/, ''));\n\n formFields.forEach(({ fieldName, fieldValue }) => {\n url.searchParams.append(fieldName, fieldValue);\n });\n\n return new Promise(() => window.location.assign(decodeURI(url.href)));\n }\n\n throw new NotImplementedError(`Unsupported action type: ${nextAction.type}`);\n }\n\n throw error;\n }\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private async _installWidget(containerId: string, config: OpyWidgetConfig): Promise {\n const widgetContainer = document.getElementById(containerId);\n\n if (widgetContainer) {\n try {\n const widget = await this._scriptLoader.loadOpyWidget(config.region);\n\n widget.Config(config);\n } catch (error) {\n return;\n }\n\n widgetContainer.appendChild(document.createElement('opy-learn-more-button'));\n }\n }\n}\n","export enum OpyRegion {\n AU = 'AU',\n UK = 'UK',\n US = 'US',\n}\n\n/**\n * https://widgets.openpay.com.au/config\n */\nexport interface OpyWidgetConfig {\n /**\n * The region your store is located in.\n */\n region: OpyRegion;\n /**\n * The currency symbol used in the widgets.\n */\n currency: '$' | '£';\n /**\n * An array of available plan tiers you have available in months.\n */\n planTiers: number[];\n /**\n * The minimum eligible amount required before Opy is eligible.\n */\n minEligibleAmount: number;\n /**\n * The maximum eligible amount required before Opy is eligible.\n */\n maxEligibleAmount: number;\n /**\n * Type of your store.\n */\n type: 'Online';\n}\n\nexport interface OpyWidget {\n /**\n * Initialize the library.\n *\n * @param config Properties with the correct purchase limits, plan tiers, etc.\n */\n Config(config: OpyWidgetConfig): void;\n}\n\nexport interface OpyHostWindow extends Window {\n /**\n * The Opy widgets library.\n */\n OpenpayWidgets?: OpyWidget;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { OpyHostWindow, OpyRegion, OpyWidget } from './opy-library';\n\nconst AU_REGION_URL = 'https://widgets.openpay.com.au/lib/openpay-widgets.min.js';\n\nconst SOURCES = {\n AU: AU_REGION_URL,\n UK: AU_REGION_URL,\n US: 'https://widgets.opy.com/lib/openpay-widgets.min.js',\n};\n\nexport default class OpyScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: OpyHostWindow = window) {}\n\n async loadOpyWidget(region = OpyRegion.AU): Promise {\n await this._scriptLoader.loadScript(SOURCES[region]);\n\n if (!this._window.OpenpayWidgets) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.OpenpayWidgets;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport PaypalScriptLoader from './paypal-script-loader';\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private _paypalSdk?: PaypalSDK;\n private _paymentMethod?: PaymentMethod;\n private _useRedirectFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _scriptLoader: PaypalScriptLoader,\n private _window: PaypalHostWindow = window,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n this._useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n if (!this._isInContextEnabled()) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._scriptLoader\n .loadPaypal()\n .then((paypal) => {\n this._paypalSdk = paypal;\n\n if (!this._paymentMethod || !this._paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._paypalSdk.checkout.setup(this._paymentMethod.config.merchantId, {\n button: 'paypal-button',\n environment: this._paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._isInContextEnabled() && this._paypalSdk) {\n this._paypalSdk.checkout.closeFlow();\n this._paypalSdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const paypal = this._paypalSdk;\n\n if (this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n }\n\n if (!this._isInContextEnabled() || this._useRedirectFlow) {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl && this._window.top) {\n this._window.top.location.href = redirectUrl;\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n });\n }\n\n if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n paypal.checkout.startFlow(redirectUrl);\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n })\n .catch((error) => {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _isAcknowledgedOrFinalized(): boolean {\n const state = this._store.getState();\n\n return (\n state.payment.getPaymentStatus() === paymentStatusTypes.ACKNOWLEDGE ||\n state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE\n );\n }\n\n private _isInContextEnabled(): boolean {\n return !!(this._paymentMethod && this._paymentMethod.config.merchantId);\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalScriptLoader {\n private _window: PaypalHostWindow;\n\n constructor(private _scriptLoader: ScriptLoader) {\n this._window = window;\n }\n\n async loadPaypal(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n };\n\n merchantId\n ? await this._scriptLoader.loadScript(scriptSrc, options)\n : await this._scriptLoader.loadScript(scriptSrc);\n\n if (!this._window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.paypal;\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"query-string\");","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\n}\n","import { exclude, ParsedUrl, parseUrl, stringifyUrl } from 'query-string';\n\nexport const PENDING_REDIRECT_PARAM = 'redirecting';\n\nexport class RedirectionState {\n private _isRedirecting: boolean;\n\n constructor() {\n this._isRedirecting = this.currentUrlHasRedirectingParam();\n }\n\n isRedirecting() {\n return this._isRedirecting;\n }\n\n setRedirecting(value: boolean) {\n if (value) {\n this.setRedirectingParamOnUrl();\n } else {\n this.removeRedirectingParamFromUrl();\n }\n\n this._isRedirecting = value;\n }\n\n private currentUrlHasRedirectingParam(): boolean {\n return PENDING_REDIRECT_PARAM in this.getCurrentUrl().query;\n }\n\n private getCurrentUrl(): ParsedUrl {\n return parseUrl(window.location.href);\n }\n\n private replaceCurrentUrl(url: string) {\n window.history.replaceState(null, '', url);\n }\n\n private setRedirectingParamOnUrl() {\n if (this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n const currentUrl = this.getCurrentUrl();\n const updatedUrl = {\n ...currentUrl,\n query: {\n ...currentUrl.query,\n [PENDING_REDIRECT_PARAM]: 'true',\n },\n };\n\n this.replaceCurrentUrl(stringifyUrl(updatedUrl));\n }\n\n private removeRedirectingParamFromUrl() {\n if (!this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n this.replaceCurrentUrl(exclude(window.location.href, [PENDING_REDIRECT_PARAM]));\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { overSome } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\nimport {\n handleHumanVerification,\n HumanVerification,\n isHumanVerification,\n} from './human-verification';\nimport { handleRedirect, isRedirect, Redirect } from './redirect';\n\nexport type Continue = Redirect | HumanVerification;\n\nconst isAnyContinue = overSome([isRedirect, isHumanVerification]);\n\nexport const isContinue = (body: PaymentsAPIResponse['body']): body is Continue =>\n isAnyContinue(body);\n\nexport interface ContinueCallbacks {\n humanVerification?(additionalAction: PaymentAdditionalAction): Promise;\n}\n\nexport class ContinueHandler {\n constructor(\n private _formPoster: FormPoster,\n private _humanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n handle(body: Continue, callbacks?: ContinueCallbacks): Promise {\n switch (body.code) {\n case 'redirect':\n return handleRedirect(body.parameters, this._formPoster);\n\n case 'resubmit_with_human_verification':\n return handleHumanVerification(\n body.parameters,\n this._humanVerificationHandler,\n callbacks?.humanVerification,\n );\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { get, isObject, isString, isUndefined, noop } from 'lodash';\n\nimport { PaymentMethodCancelledError } from '../../../../../errors';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\nimport { RedirectionState } from './RedirectionState';\n\ninterface Parameters {\n url: string;\n form_fields?: Record;\n}\n\nexport interface Redirect {\n type: 'continue';\n code: 'redirect';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const formFields = get(x, 'form_fields');\n\n return isString(get(x, 'url')) && (isUndefined(formFields) || isObject(formFields));\n};\n\nexport const isRedirect = (body: PaymentsAPIResponse['body']): body is Redirect =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'redirect' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleRedirect = (\n { url, form_fields }: Parameters,\n formPoster: FormPoster,\n): Promise => {\n const redirectionState = new RedirectionState();\n\n if (redirectionState.isRedirecting()) {\n redirectionState.setRedirecting(false);\n\n return Promise.reject(new PaymentMethodCancelledError());\n }\n\n redirectionState.setRedirecting(true);\n\n if (form_fields) {\n formPoster.postForm(url, form_fields);\n } else {\n window.location.assign(url);\n }\n\n return new Promise(noop);\n};\n","import { get, isArray } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\ninterface VerificationMethod {\n id: string;\n parameters: Record;\n}\n\ninterface Parameters {\n available_methods: VerificationMethod[];\n}\n\nexport interface HumanVerification {\n type: 'continue';\n code: 'resubmit_with_human_verification';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const availableMethods = get(x, 'available_methods');\n\n return isArray(availableMethods);\n};\n\nexport const isHumanVerification = (body: PaymentsAPIResponse['body']): body is HumanVerification =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'resubmit_with_human_verification' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleHumanVerification = async (\n { available_methods }: Parameters,\n humanVerificationHandler?: PaymentHumanVerificationHandler,\n callback?: (additionalAction: PaymentAdditionalAction) => Promise,\n): Promise => {\n if (!callback) {\n throw new Error('PPSDK human verification callback function is missing.');\n }\n\n if (!humanVerificationHandler) {\n throw new Error('PPSDK human verification handler is missing.');\n }\n\n if (available_methods.length === 0) {\n throw Error('Human verification method is missing.');\n }\n\n // Only one method is expected because google recaptcha only is supported\n const { id, parameters } = available_methods[0];\n\n const additionalAction: PaymentAdditionalAction = await humanVerificationHandler.handle(\n id,\n parameters.key,\n );\n\n return callback(additionalAction);\n};\n","import { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nimport { ContinueCallbacks, ContinueHandler, isContinue } from './continue-handler';\nimport { handleError, isError } from './error';\nimport { handleFailure, isFailure } from './failure';\nimport { handleSuccess, isSuccess } from './success';\nimport { handleUnsupported } from './unsupported';\n\ninterface StepHandlerCallbacks {\n continue?: ContinueCallbacks;\n}\n\nexport class StepHandler {\n constructor(private _continueHandler: ContinueHandler) {}\n\n handle(response: PaymentsAPIResponse, callbacks?: StepHandlerCallbacks): Promise {\n const { body } = response;\n\n if (isSuccess(body)) {\n return handleSuccess();\n }\n\n if (isContinue(body)) {\n return this._continueHandler.handle(body, callbacks?.continue);\n }\n\n if (isFailure(response)) {\n return handleFailure(response);\n }\n\n if (isError(response)) {\n return handleError(response);\n }\n\n return handleUnsupported(response);\n }\n}\n","import { get } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface Success {\n type: 'success';\n}\n\nexport const isSuccess = (body: PaymentsAPIResponse['body']): body is Success =>\n get(body, 'type') === 'success';\n\nexport const handleSuccess = () => Promise.resolve();\n","import { get, isString } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface FailureResponse extends PaymentsAPIResponse {\n body: {\n type: 'failure';\n code: string;\n };\n}\n\nexport const isFailure = (response: PaymentsAPIResponse): response is FailureResponse =>\n get(response.body, 'type') === 'failure' && isString(get(response.body, 'code'));\n\nconst toRequestErrorFormat = (failureResponse: FailureResponse) => ({\n ...failureResponse,\n body: {\n errors: [{ code: failureResponse.body.code }],\n },\n});\n\nexport const handleFailure = (response: FailureResponse): Promise =>\n Promise.reject(new RequestError(toRequestErrorFormat(response)));\n","import { get } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface ErrorResponse extends PaymentsAPIResponse {\n body: {\n type: 'error';\n };\n}\n\nexport const isError = (response: PaymentsAPIResponse): response is ErrorResponse =>\n get(response.body, 'type') === 'error';\n\nexport const handleError = (response: ErrorResponse) => Promise.reject(new RequestError(response));\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentHumanVerificationHandler } from '../../../../spam-protection';\n\nimport { ContinueHandler } from './continue-handler';\nimport { StepHandler } from './step-handler';\n\nexport const createStepHandler = (\n formPoster: FormPoster,\n humanVerificationHandler: PaymentHumanVerificationHandler,\n) => new StepHandler(new ContinueHandler(formPoster, humanVerificationHandler));\n","import { BrowserStorage } from '../../../common/storage';\n\ntype CompletedPayments = string[];\n\nconst COMPLETED_PAYMENTS_KEY = 'completed-payments';\n\nexport class PPSDKCompletedPayments {\n constructor(private _browserStorage: BrowserStorage) {}\n\n isCompleted(paymentId: string): boolean {\n return this.getCompletedPayments().indexOf(paymentId) >= 0;\n }\n\n setCompleted(paymentId: string): void {\n const completedPayments = this.getCompletedPayments();\n\n completedPayments.push(paymentId);\n\n this.setCompletedPayments(completedPayments);\n }\n\n private getCompletedPayments(): CompletedPayments {\n return this._browserStorage.getItem(COMPLETED_PAYMENTS_KEY) || [];\n }\n\n private setCompletedPayments(completedPayments: CompletedPayments): void {\n this._browserStorage.setItem(COMPLETED_PAYMENTS_KEY, completedPayments);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { BrowserStorage } from '../../../common/storage';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { getPPSDKMethod } from './get-ppsdk-payment-method';\nimport { PPSDKCompletedPayments } from './ppsdk-completed-payments';\nimport { PaymentResumer } from './ppsdk-payment-resumer';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\n\nexport class PPSDKStrategy implements PaymentStrategy {\n private _subStrategy?: SubStrategy;\n private _completedPayments: PPSDKCompletedPayments;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _subStrategyRegistry: SubStrategyRegistry,\n private _paymentResumer: PaymentResumer,\n browserStorage: BrowserStorage,\n ) {\n this._completedPayments = new PPSDKCompletedPayments(browserStorage);\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n const { payment, ...order } = payload;\n const { _subStrategy: subStrategy } = this;\n\n if (!subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const token = this._store.getState().order.getOrderMeta()?.token;\n\n if (!token) {\n throw new MissingDataError(MissingDataErrorType.MissingOrder);\n }\n\n await subStrategy.execute({ methodId, payment, bigpayBaseUrl, token });\n\n return this._store.getState();\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const order = this._store.getState().order.getOrderOrThrow();\n\n if (order.isComplete) {\n return this._store.getState();\n }\n\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentId = this._store.getState().order.getPaymentId(options.methodId);\n\n if (!paymentId || !order || this._completedPayments.isCompleted(paymentId)) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const { orderId } = order;\n\n await this._paymentResumer.resume({ paymentId, bigpayBaseUrl, orderId }).catch((error) => {\n this._completedPayments.setCompleted(paymentId);\n throw error;\n });\n\n return this._store.getState();\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n if (!paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._subStrategy = this._subStrategyRegistry.getByMethod(paymentMethod);\n\n if (!this._subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._subStrategy.initialize(options);\n\n return this._store.getState();\n }\n\n async deinitialize(_options?: PaymentRequestOptions): Promise {\n this._subStrategy?.deinitialize();\n\n return this._store.getState();\n }\n}\n","import { CheckoutStore } from '../../../checkout';\nimport { isPPSDKPaymentMethod, PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\ntype GetPPSDKMethod = (store: CheckoutStore, methodId: string) => PPSDKPaymentMethod | undefined;\n\nexport const getPPSDKMethod: GetPPSDKMethod = (store, methodId) => {\n const paymentMethod = store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !isPPSDKPaymentMethod(paymentMethod)) {\n return;\n }\n\n return paymentMethod;\n};\n","import { cond, constant, stubTrue } from 'lodash';\n\nimport { Registry } from '../../../common/registry';\nimport { PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\nimport { isCard, isNone } from './initialization-strategies';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\n\nconst getToken = cond([\n [isCard, constant(SubStrategyType.CARD)],\n [isNone, constant(SubStrategyType.NONE)],\n [stubTrue, constant(SubStrategyType.UNSUPPORTED)],\n]);\n\nexport class SubStrategyRegistry extends Registry {\n getByMethod(paymentMethod: PPSDKPaymentMethod): SubStrategy | undefined {\n const token = getToken(paymentMethod.initializationStrategy);\n\n return this.get(token);\n }\n}\n","import { InitializationStrategy } from '../../../';\n\ninterface Card {\n type: 'card_ui';\n}\n\nexport const isCard = (strategy: Pick): strategy is Card =>\n strategy.type === 'card_ui';\n","import { InitializationStrategy } from '../../../';\n\ninterface None {\n type: 'none';\n}\n\nexport const isNone = (strategy: Pick): strategy is None =>\n strategy.type === 'none';\n","import { CheckoutStore } from '../../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../../hosted-form';\nimport { OrderActionCreator } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport PaymentAdditionalAction from '../../../payment-additional-action';\nimport { PaymentInitializeOptions } from '../../../payment-request-options';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class CardSubStrategy implements SubStrategy {\n protected _hostedForm?: HostedForm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _ppsdkStepHandler: StepHandler,\n ) {}\n\n async execute(settings: SubStrategySettings): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { additionalAction, payment } = settings;\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await form.validate();\n\n const { payload } = await form.submit(payment, additionalAction);\n\n const { response } = payload;\n\n const humanVerificationCallback = async (\n additionalAction: PaymentAdditionalAction,\n ): Promise => this.execute({ additionalAction, ...settings });\n\n await this._ppsdkStepHandler.handle(response, {\n continue: {\n humanVerification: humanVerificationCallback,\n },\n });\n\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions);\n\n await form.attach();\n\n this._hostedForm = form;\n }\n\n deinitialize(): void {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class NoneSubStrategy implements SubStrategy {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n execute({ methodId, bigpayBaseUrl, token }: SubStrategySettings): Promise {\n const body = { payment_method_id: methodId };\n const options = {\n credentials: false,\n body,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .post(`${bigpayBaseUrl}/payments`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): void {}\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator } from '../../../order';\n\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\nimport { StepHandler } from './step-handler';\nimport { CardSubStrategy, NoneSubStrategy } from './sub-strategies';\n\nexport const createSubStrategyRegistry = (\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n requestSender: RequestSender,\n stepHandler: StepHandler,\n hostedFormFactory: HostedFormFactory,\n) => {\n const registry = new SubStrategyRegistry();\n\n registry.register(\n SubStrategyType.CARD,\n () => new CardSubStrategy(store, orderActionCreator, hostedFormFactory, stepHandler),\n );\n\n registry.register(SubStrategyType.NONE, () => new NoneSubStrategy(requestSender, stepHandler));\n\n registry.register(SubStrategyType.UNSUPPORTED, () => undefined);\n\n return registry;\n};\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\n\nimport { PaymentsAPIResponse } from './ppsdk-payments-api-response';\nimport { StepHandler } from './step-handler';\n\ninterface ResumeSettings {\n orderId: number;\n paymentId: string;\n bigpayBaseUrl: string;\n}\n\nexport class PaymentResumer {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n async resume({ paymentId, bigpayBaseUrl, orderId }: ResumeSettings): Promise {\n const token = await this._getToken(orderId).catch(() => {\n throw new OrderFinalizationNotRequiredError();\n });\n\n const options = {\n credentials: false,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .get(`${bigpayBaseUrl}/payments/${paymentId}`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n private async _getToken(orderId: number): Promise {\n const url = `/api/storefront/payments/auth-token`;\n const options = {\n params: {\n order_id: orderId,\n },\n };\n\n return this._requestSender\n .get<{ auth_token: string }>(url, options)\n .then(({ body }) => body.auth_token);\n }\n}\n","import { merge } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport WepayRiskClient from './wepay-risk-client';\n\nexport default class WepayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n void this._wepayRiskClient.initialize();\n\n return super.initialize(options);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const token = this._wepayRiskClient.getRiskToken();\n const payloadWithToken = merge({}, payload, {\n payment: {\n paymentData: {\n deviceSessionId: token,\n },\n },\n });\n\n return super.execute(payloadWithToken, options);\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport WepayRisk from './wepay-risk';\nimport WepayWindow from './wepay-window';\n\nconst SCRIPT_SRC = '//static.wepay.com/min/js/risk.1.latest.js';\n\nexport default class WepayRiskClient {\n private _riskClient?: WepayRisk;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n initialize(): Promise {\n return this._scriptLoader\n .loadScript(SCRIPT_SRC)\n .then(() => (this._riskClient = (window as unknown as WepayWindow).WePay.risk))\n .then(() => this);\n }\n\n getRiskToken(): string {\n if (!this._riskClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._riskClient.generate_risk_token();\n\n return this._riskClient.get_risk_token();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody } from './instrument-response-body';\n\nexport enum InstrumentActionType {\n LoadInstrumentsRequested = 'LOAD_INSTRUMENTS_REQUESTED',\n LoadInstrumentsSucceeded = 'LOAD_INSTRUMENTS_SUCCEEDED',\n LoadInstrumentsFailed = 'LOAD_INSTRUMENTS_FAILED',\n\n DeleteInstrumentRequested = 'DELETE_INSTRUMENT_REQUESTED',\n DeleteInstrumentSucceeded = 'DELETE_INSTRUMENT_SUCCEEDED',\n DeleteInstrumentFailed = 'DELETE_INSTRUMENT_FAILED',\n}\n\nexport type InstrumentAction = LoadInstrumentsAction | DeleteInstrumentAction;\n\nexport type LoadInstrumentsAction =\n | LoadInstrumentsRequestedAction\n | LoadInstrumentsSucceededAction\n | LoadInstrumentsFailedAction;\n\nexport type DeleteInstrumentAction =\n | DeleteInstrumentRequestedAction\n | DeleteInstrumentSucceededAction\n | DeleteInstrumentFailedAction;\n\nexport interface LoadInstrumentsRequestedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsRequested;\n}\n\nexport interface LoadInstrumentsSucceededAction\n extends Action {\n type: InstrumentActionType.LoadInstrumentsSucceeded;\n}\n\nexport interface LoadInstrumentsFailedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsFailed;\n}\n\nexport interface DeleteInstrumentRequestedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentRequested;\n}\n\nexport interface DeleteInstrumentSucceededAction\n extends Action {\n type: InstrumentActionType.DeleteInstrumentSucceeded;\n}\n\nexport interface DeleteInstrumentFailedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { Address } from '../../address';\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../../checkout';\nimport { addMinutes, isFuture } from '../../common/date-time';\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\n\nimport { SessionContext, VaultAccessToken } from './instrument';\nimport {\n DeleteInstrumentAction,\n InstrumentActionType,\n LoadInstrumentsAction,\n} from './instrument-actions';\nimport InstrumentRequestSender from './instrument-request-sender';\n\nexport default class InstrumentActionCreator {\n constructor(private _instrumentRequestSender: InstrumentRequestSender) {}\n\n loadInstruments(): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(InstrumentActionType.LoadInstrumentsRequested));\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n const shippingAddress = this._getShippingAddress(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .loadInstruments(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n shippingAddress,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.LoadInstrumentsSucceeded,\n body,\n currentToken,\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(InstrumentActionType.LoadInstrumentsFailed, response),\n );\n });\n });\n }\n\n deleteInstrument(\n instrumentId: string,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(\n createAction(InstrumentActionType.DeleteInstrumentRequested, undefined, {\n instrumentId,\n }),\n );\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .deleteInstrument(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n instrumentId,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.DeleteInstrumentSucceeded,\n body,\n {\n instrumentId,\n ...currentToken,\n },\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(\n InstrumentActionType.DeleteInstrumentFailed,\n response,\n { instrumentId },\n ),\n );\n });\n });\n }\n\n private _isValidVaultAccessToken(token: VaultAccessToken): boolean {\n if (!token || !token.vaultAccessToken) {\n return false;\n }\n\n const expiryBuffer = 2;\n const expiry = addMinutes(new Date(token.vaultAccessExpiry), expiryBuffer);\n\n return isFuture(expiry);\n }\n\n private _getCurrentAccessToken(store: ReadableCheckoutStore): VaultAccessToken | undefined {\n const { instruments } = store.getState();\n const meta = instruments.getInstrumentsMeta();\n\n if (!meta) {\n return;\n }\n\n return {\n vaultAccessToken: meta.vaultAccessToken,\n vaultAccessExpiry: meta.vaultAccessExpiry,\n };\n }\n\n private _getValidAccessToken(token?: VaultAccessToken): Promise {\n return token && this._isValidVaultAccessToken(token)\n ? Promise.resolve(token)\n : this._instrumentRequestSender.getVaultAccessToken().then(({ body }) => body);\n }\n\n private _getShippingAddress(store: ReadableCheckoutStore): Address | Address[] | undefined {\n const state = store.getState();\n const addresses = state.shippingAddress.getShippingAddresses();\n\n return addresses.length > 1 ? addresses : state.shippingAddress.getShippingAddress();\n }\n\n private _getSessionContext(store: ReadableCheckoutStore): SessionContext {\n const state = store.getState();\n const config = state.config.getStoreConfig();\n const cart = state.cart.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { customerId } = cart;\n const { storeId } = config.storeProfile;\n const { code } = config.shopperCurrency.isTransactional\n ? config.shopperCurrency\n : config.currency;\n\n return {\n customerId,\n storeId,\n currencyCode: code,\n };\n }\n}\n","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\n}\n","export default function addMinutes(date: Date, amount: number): Date {\n const newDate = new Date(date.getTime());\n\n newDate.setMinutes(date.getMinutes() + amount);\n\n return newDate;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentResponse from '../payment-response';\n\nimport PaymentInstrument, { VaultAccessToken } from './instrument';\nimport {\n BankInternalInstrument,\n InstrumentErrorResponseBody,\n InstrumentsResponseBody,\n InternalInstrument,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n PayPalInternalInstrument,\n} from './instrument-response-body';\nimport { mapToBankInstrument } from './map-to-bank-instrument';\nimport { mapToCardInstrument } from './map-to-card-instrument';\nimport { mapToPayPalInstrument } from './map-to-paypal-instrument';\n\nexport default class InstrumentResponseTransformer {\n transformResponse(\n response: PaymentResponse,\n ): Response {\n const { body, ...payload } = this._transformResponse(response);\n\n return {\n ...payload,\n body: {\n vaultedInstruments: this._transformVaultedInstruments(body.vaulted_instruments),\n },\n };\n }\n\n transformErrorResponse(\n response: PaymentResponse,\n ): Response {\n return this._transformResponse(response);\n }\n\n transformVaultAccessResponse(\n response: Response,\n ): Response {\n return {\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n };\n }\n\n private _transformVaultedInstruments(\n vaultedInstruments: InternalInstrument[] = [],\n ): PaymentInstrument[] {\n return vaultedInstruments.map((instrument) => {\n if (this._isPayPalInstrument(instrument)) {\n return mapToPayPalInstrument(instrument);\n }\n\n if (this._isBankInstrument(instrument)) {\n return mapToBankInstrument(instrument);\n }\n\n return mapToCardInstrument(instrument);\n });\n }\n\n private _isPayPalInstrument(\n instrument: InternalInstrument,\n ): instrument is PayPalInternalInstrument {\n return instrument.method_type === 'paypal';\n }\n\n private _isBankInstrument(\n instrument: InternalInstrument,\n ): instrument is BankInternalInstrument {\n return instrument.method_type === 'bank';\n }\n\n private _transformResponse(response: PaymentResponse): Response {\n const { data: body, ...payload } = response;\n\n return {\n ...payload,\n body,\n };\n }\n}\n","import { PayPalInstrument } from './instrument';\nimport { PayPalInternalInstrument } from './instrument-response-body';\n\nexport function mapToPayPalInstrument(instrument: PayPalInternalInstrument): PayPalInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n externalId: instrument.external_id,\n trustedShippingAddress: instrument.trusted_shipping_address,\n method: 'paypal',\n type: 'account',\n };\n}\n","import { BankInstrument } from './instrument';\nimport { BankInternalInstrument } from './instrument-response-body';\n\nexport function mapToBankInstrument(instrument: BankInternalInstrument): BankInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n trustedShippingAddress: instrument.trusted_shipping_address,\n accountNumber: instrument.account_number,\n issuer: instrument.issuer,\n iban: instrument.iban,\n method: instrument.method,\n type: 'bank',\n };\n}\n","import { CardInstrument } from './instrument';\nimport { CardInternalInstrument } from './instrument-response-body';\n\nexport function mapToCardInstrument(instrument: CardInternalInstrument): CardInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n iin: instrument.iin,\n last4: instrument.last_4,\n expiryMonth: instrument.expiry_month,\n expiryYear: instrument.expiry_year,\n brand: instrument.brand,\n trustedShippingAddress: instrument.trusted_shipping_address,\n untrustedShippingCardVerificationMode:\n instrument.untrusted_shipping_address_card_verification_mode,\n method: instrument.method,\n type: 'card',\n };\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Address, mapToInternalAddress } from '../../address';\nimport { RequestOptions } from '../../common/http-request';\nimport PaymentResponse from '../payment-response';\n\nimport { InstrumentRequestContext, VaultAccessToken } from './instrument';\nimport {\n InstrumentsResponseBody,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n} from './instrument-response-body';\nimport InstrumentResponseTransformer from './instrument-response-transformer';\n\nexport default class InstrumentRequestSender {\n private _transformer: InstrumentResponseTransformer;\n\n constructor(private _client: any, private _requestSender: RequestSender) {\n this._transformer = new InstrumentResponseTransformer();\n }\n\n getVaultAccessToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/checkout/payments/vault-access-token';\n\n return this._requestSender\n .get(url, { timeout })\n .then((response) => ({\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n }));\n }\n\n loadInstruments(\n requestContext: InstrumentRequestContext,\n shippingAddress?: Address | Address[],\n ): Promise> {\n return shippingAddress\n ? this._loadInstrumentsWithAddress(requestContext, shippingAddress)\n : this._loadInstruments(requestContext);\n }\n\n deleteInstrument(\n requestContext: InstrumentRequestContext,\n instrumentId: string,\n ): Promise> {\n const payload = {\n ...requestContext,\n instrumentId,\n };\n\n return new Promise((resolve, reject) => {\n this._client.deleteShopperInstrument(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstruments(\n requestContext: InstrumentRequestContext,\n ): Promise> {\n return new Promise((resolve, reject) => {\n this._client.loadInstruments(\n requestContext,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstrumentsWithAddress(\n requestContext: InstrumentRequestContext,\n shippingAddress: Address | Address[],\n ): Promise> {\n const payload = {\n ...requestContext,\n shippingAddress: Array.isArray(shippingAddress)\n ? shippingAddress.map((address) => mapToInternalAddress(address))\n : mapToInternalAddress(shippingAddress),\n };\n\n return new Promise((resolve, reject) => {\n this._client.loadInstrumentsWithAddress(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { PickupOptionMeta, PickupOptionResult } from './pickup-option';\n\nexport enum PickupOptionActionType {\n LoadPickupOptionsRequested = 'LOAD_PICKUP_OPTIONS_REQUESTED',\n LoadPickupOptionsSucceeded = 'LOAD_PICKUP_OPTIONS_SUCCEEDED',\n LoadPickupOptionsFailed = 'LOAD_PICKUP_OPTIONS_FAILED',\n}\n\nexport type LoadPickupOptionsAction =\n | PickupOptionRequestedAction\n | LoadPickupOptionsSucceededAction\n | LoadPickupOptionsFailedAction;\n\nexport interface PickupOptionRequestedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsRequested;\n}\n\nexport interface LoadPickupOptionsSucceededAction\n extends Action {\n type: PickupOptionActionType.LoadPickupOptionsSucceeded;\n}\n\nexport interface LoadPickupOptionsFailedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsFailed;\n}\n","import {\n createAction,\n createErrorAction,\n ReadableDataStore,\n ThunkAction,\n} from '@bigcommerce/data-store';\nimport { includes } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { LineItem } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { PickupOptionAPIRequestBody, PickupOptionRequestBody } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionRequestSender from './pickup-option-request-sender';\n\nexport default class PickupOptionActionCreator {\n constructor(private _pickupOptionRequestSender: PickupOptionRequestSender) {}\n\n loadPickupOptions(\n query: PickupOptionRequestBody,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const apiQuery = this._hydrateApiQuery(store, query);\n\n observer.next(createAction(PickupOptionActionType.LoadPickupOptionsRequested));\n\n this._pickupOptionRequestSender\n .fetchPickupOptions(apiQuery)\n .then((response) => {\n observer.next(\n createAction(\n PickupOptionActionType.LoadPickupOptionsSucceeded,\n response.body.results,\n query,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PickupOptionActionType.LoadPickupOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _hydrateApiQuery(\n store: ReadableDataStore,\n query: PickupOptionRequestBody,\n ): PickupOptionAPIRequestBody {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const consignment = state.consignments.getConsignmentById(query.consignmentId);\n\n if (!consignment) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentLineItems = consignment.lineItemIds;\n const physicalItems = cart.lineItems.physicalItems;\n const cartItems = physicalItems\n .filter((item: LineItem) => includes(consignmentLineItems, item.id))\n .map((item) => ({\n variantId: item.variantId,\n quantity: item.quantity,\n }));\n\n return {\n searchArea: query.searchArea,\n items: cartItems,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { PickupOptionAPIRequestBody, PickupOptionResponse } from './pickup-option';\n\nconst url = '/api/storefront/pickup-options';\n\nexport default class PickupOptionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n fetchPickupOptions(query: PickupOptionAPIRequestBody): Promise> {\n return this._requestSender.post(url, {\n headers: { Accept: ContentType.Json, ...SDK_VERSION_HEADERS },\n body: query,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ShippingStrategyActionType {\n UpdateAddressFailed = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED',\n UpdateAddressRequested = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED',\n UpdateAddressSucceeded = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED',\n SelectOptionFailed = 'SHIPPING_STRATEGY_SELECT_OPTION_FAILED',\n SelectOptionRequested = 'SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED',\n SelectOptionSucceeded = 'SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED',\n InitializeFailed = 'SHIPPING_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'SHIPPING_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'SHIPPING_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type ShippingStrategyAction =\n | ShippingStrategyUpdateAddressAction\n | ShippingStrategySelectOptionAction\n | ShippingStrategyInitializeAction\n | ShippingStrategyDeinitializeAction\n | ShippingStrategyWidgetAction;\n\nexport type ShippingStrategyUpdateAddressAction =\n | UpdateAddressRequestedAction\n | UpdateAddressSucceededAction\n | UpdateAddressFailedAction;\n\nexport type ShippingStrategySelectOptionAction =\n | SelectOptionRequestedAction\n | SelectOptionSucceededAction\n | SelectOptionFailedAction;\n\nexport type ShippingStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type ShippingStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type ShippingStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface UpdateAddressRequestedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressRequested;\n}\n\nexport interface UpdateAddressSucceededAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressSucceeded;\n}\n\nexport interface UpdateAddressFailedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressFailed;\n}\n\nexport interface SelectOptionRequestedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionRequested;\n}\n\nexport interface SelectOptionSucceededAction extends Action {\n type: ShippingStrategyActionType.SelectOptionSucceeded;\n}\n\nexport interface SelectOptionFailedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: ShippingStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport { ShippingInitializeOptions, ShippingRequestOptions } from './shipping-request-options';\nimport {\n ShippingStrategyAction,\n ShippingStrategyActionType,\n ShippingStrategyDeinitializeAction,\n ShippingStrategyInitializeAction,\n ShippingStrategySelectOptionAction,\n ShippingStrategyUpdateAddressAction,\n} from './shipping-strategy-actions';\nimport { ShippingStrategy } from './strategies';\n\nexport default class ShippingStrategyActionCreator {\n constructor(private _strategyRegistry: Registry) {}\n\n updateAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .updateAddress(address, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.UpdateAddressSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.UpdateAddressFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n selectOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.SelectOptionRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .selectOption(shippingOptionId, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.SelectOptionSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.SelectOptionFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n initialize(\n options?: ShippingInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n const mergedOptions = { ...options, methodId };\n\n if (methodId && state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.InitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .initialize(mergedOptions)\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.InitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(ShippingStrategyActionType.InitializeFailed, error, {\n methodId,\n }),\n );\n });\n });\n }\n\n deinitialize(\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n if (methodId && !state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .deinitialize({ ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.DeinitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.DeinitializeFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: ShippingRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(ShippingStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this._window.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this._window, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n getElements(stripeClient: StripeUPEClient, options: StripeElementsOptions): StripeElements {\n let stripeElements = this._window.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this._window, { bcStripeElements: stripeElements });\n } else {\n stripeElements.fetchUpdates();\n stripeElements.update(options);\n }\n\n return stripeElements;\n }\n\n private async load() {\n await this._scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe;\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2PaymentProcessor,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\n\nimport { ConsignmentActionCreator, ShippingStrategyActionCreator } from '../..';\nimport { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class AmazonPayV2ShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n const updateAddressRequestBody = {\n ...shippingAddress,\n customFields: address.customFields,\n };\n\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options),\n );\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { amazonpay, methodId } = options;\n\n if (!amazonpay || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.amazonpay\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n const { paymentToken, region } = paymentMethod.initializationData;\n const buttonId = amazonpay.editAddressButtonId;\n\n if (paymentToken && buttonId) {\n const shouldShowLoadingSpinner = this._shouldShowLoadingSpinner(region);\n\n this._bindEditButton(buttonId, paymentToken, 'changeAddress', shouldShowLoadingSpinner);\n }\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _bindEditButton(\n id: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n shouldShowLoadingSpinner: boolean,\n ): void {\n const button = document.getElementById(id);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (shouldShowLoadingSpinner) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._shippingStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _shouldShowLoadingSpinner(region: string) {\n return region !== 'us';\n }\n}\n","type PaymentInstrument = CardInstrument | AccountInstrument;\n\nexport default PaymentInstrument;\n\ninterface BaseInstrument {\n bigpayToken: string;\n defaultInstrument: boolean;\n provider: string;\n trustedShippingAddress: boolean;\n method: string;\n type: string;\n}\n\nexport enum UntrustedShippingCardVerificationType {\n CVV = 'cvv',\n PAN = 'pan',\n}\n\nexport interface CardInstrument extends BaseInstrument {\n brand: string;\n expiryMonth: string;\n expiryYear: string;\n iin: string;\n last4: string;\n type: 'card';\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType;\n}\n\ninterface BaseAccountInstrument extends BaseInstrument {\n method: string;\n type: 'account' | 'bank';\n}\n\nexport interface PayPalInstrument extends BaseAccountInstrument {\n externalId: string;\n method: 'paypal';\n}\n\nexport interface AchInstrument extends BaseAccountInstrument {\n issuer: string;\n accountNumber: string;\n type: 'bank';\n method: 'ach' | 'ecp';\n}\n\nexport interface BankInstrument extends BaseAccountInstrument {\n accountNumber: string;\n issuer: string;\n iban: string;\n method: string;\n type: 'bank';\n}\n\nexport type AccountInstrument = PayPalInstrument | BankInstrument | AchInstrument;\n\nexport interface VaultAccessToken {\n vaultAccessToken: string;\n vaultAccessExpiry: number;\n}\n\nexport interface SessionContext {\n customerId: number;\n storeId: string;\n currencyCode?: string;\n}\n\nexport interface InstrumentRequestContext extends SessionContext {\n authToken: string;\n}\n","import { isEqual, omit } from 'lodash';\n\nimport {\n BraintreeFastlaneAddress,\n BraintreeFastlaneAuthenticationState,\n BraintreeFastlaneProfileData,\n BraintreeFastlaneStylesOption,\n BraintreeFastlaneVaultedInstrument,\n BraintreeIntegrationService,\n getFastlaneStyles,\n isBraintreeAcceleratedCheckoutCustomer,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { BrowserStorage } from '@bigcommerce/checkout-sdk/storage';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { CustomerAddress } from '../../../customer';\nimport { Country } from '../../../geography';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { PaymentProviderCustomerActionCreator } from '../../../payment-provider-customer';\nimport { CardInstrument } from '../../../payment/instrument';\nimport { UntrustedShippingCardVerificationType } from '../../../payment/instrument/instrument';\nimport { BraintreeInitializationData } from '../../../payment/strategies/braintree';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class BraintreeFastlaneShippingStrategy implements ShippingStrategy {\n private _browserStorage: BrowserStorage;\n\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _braintreeIntegrationService: BraintreeIntegrationService,\n ) {\n this._browserStorage = new BrowserStorage('paypalFastlane');\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { methodId, braintreefastlane } = options || {};\n const { onPayPalFastlaneAddressChange } = braintreefastlane || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const customer = state.customer.getCustomerOrThrow();\n\n if (!customer.isGuest) {\n return Promise.resolve(this._store.getState());\n }\n\n try {\n if (this._shouldRunAuthenticationFlow()) {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const { clientToken, isFastlaneStylingEnabled } =\n paymentMethod?.initializationData || {};\n\n if (!clientToken) {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n }\n\n const paypalFastlaneStylesSettings = isFastlaneStylingEnabled\n ? paymentMethod?.initializationData?.fastlaneStyles\n : undefined;\n\n const fastlaneStyles = getFastlaneStyles(\n paypalFastlaneStylesSettings,\n braintreefastlane?.styles,\n );\n\n await this._runAuthenticationFlowOrThrow(methodId, fastlaneStyles);\n }\n\n if (\n typeof onPayPalFastlaneAddressChange === 'function' &&\n (await this._shouldUseBraintreeFastlaneShippingComponent(methodId))\n ) {\n onPayPalFastlaneAddressChange(() =>\n this._handleBraintreeFastlaneShippingAddressChange(),\n );\n }\n } catch (error) {\n // Info: we should not throw any error here to avoid\n // customer stuck on shipping step due to the payment provider\n // custom flow\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private _shouldRunAuthenticationFlow(): boolean {\n const state = this._store.getState();\n const cartId = state.cart.getCart()?.id;\n const paypalFastlaneSessionId = this._browserStorage.getItem('sessionId');\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n if (\n braintreePaymentProviderCustomer?.authenticationState ===\n BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n return false;\n }\n\n return (\n !braintreePaymentProviderCustomer?.authenticationState &&\n paypalFastlaneSessionId === cartId\n );\n }\n\n private async _runAuthenticationFlowOrThrow(\n methodId: string,\n styles?: BraintreeFastlaneStylesOption,\n ): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const countries = state.countries.getCountries() || [];\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const { clientToken, config } = paymentMethod;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeIntegrationService.initialize(clientToken);\n\n const braintreeFastlane = await this._braintreeIntegrationService.getBraintreeFastlane(\n cart?.id,\n config?.testMode,\n styles,\n );\n\n const customerEmail =\n state.customer.getCustomer()?.email || state.billingAddress.getBillingAddress()?.email;\n\n if (!customerEmail) {\n return;\n }\n\n const { lookupCustomerByEmail, triggerAuthenticationFlow } = braintreeFastlane.identity;\n\n const { customerContextId } = await lookupCustomerByEmail(customerEmail);\n\n if (!customerContextId) {\n return;\n }\n\n const { authenticationState, profileData } = await triggerAuthenticationFlow(\n customerContextId,\n );\n\n if (authenticationState === BraintreeFastlaneAuthenticationState.CANCELED) {\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses: [],\n instruments: [],\n }),\n );\n\n this._browserStorage.removeItem('sessionId');\n\n return;\n }\n\n const paypalBillingAddress = this._getPayPalBillingAddress(profileData);\n const paypalShippingAddress = profileData.shippingAddress;\n const paypalPhoneNumber = profileData.shippingAddress.phoneNumber;\n\n const shippingAddress = this._mapPayPalToBcAddress(\n paypalShippingAddress,\n countries,\n paypalPhoneNumber,\n );\n const billingAddress = this._mapPayPalToBcAddress(\n paypalBillingAddress,\n countries,\n paypalPhoneNumber,\n );\n\n if (billingAddress && shippingAddress) {\n const addresses = this._mergeShippingAndBillingAddresses(\n shippingAddress,\n billingAddress,\n );\n const instrument = this._mapPayPalToBcInstrument(methodId, profileData.card);\n const instruments = instrument ? [instrument] : [];\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n }),\n );\n\n if (billingAddress) {\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress({\n ...billingAddress,\n id: String(billingAddress.id),\n }),\n );\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n }\n }\n }\n\n private _getPayPalBillingAddress(\n profileData: BraintreeFastlaneProfileData,\n ): BraintreeFastlaneAddress {\n const { name, card } = profileData;\n const paypalBillingAddress = card.paymentSource.card.billingAddress;\n\n return {\n ...paypalBillingAddress,\n firstName: paypalBillingAddress.firstName || name?.firstName,\n lastName: paypalBillingAddress.lastName || name?.lastName,\n };\n }\n\n private _getCountryNameByCountryCode(countryCode: string, countries: Country[]): string {\n const matchedCountry = countries.find((country) => country.code === countryCode);\n\n return matchedCountry?.name || '';\n }\n\n private _mapPayPalToBcAddress(\n address: BraintreeFastlaneAddress,\n countries: Country[],\n phoneNumber?: string,\n customFields?: CustomerAddress['customFields'],\n ): CustomerAddress {\n return {\n id: Number(Date.now()),\n type: 'paypal-address',\n firstName: address.firstName || '',\n lastName: address.lastName || '',\n company: address.company || '',\n address1: address.streetAddress,\n address2: address.extendedAddress || '',\n city: address.locality,\n stateOrProvince: address.region,\n stateOrProvinceCode: address.region,\n country: this._getCountryNameByCountryCode(address.countryCodeAlpha2, countries),\n countryCode: address.countryCodeAlpha2,\n postalCode: address.postalCode,\n phone: phoneNumber || '',\n customFields: customFields || [],\n };\n }\n\n private _normalizeAddress(address: CustomerAddress | BraintreeFastlaneAddress) {\n return omit(address, ['id']);\n }\n\n private _mergeShippingAndBillingAddresses(\n shippingAddress: CustomerAddress,\n billingAddress: CustomerAddress,\n ): CustomerAddress[] {\n const addressesAreTheSame = isEqual(\n this._normalizeAddress(shippingAddress),\n this._normalizeAddress(billingAddress),\n );\n\n return addressesAreTheSame ? [shippingAddress] : [shippingAddress, billingAddress];\n }\n\n private _mapPayPalToBcInstrument(\n methodId: string,\n instrument?: BraintreeFastlaneVaultedInstrument,\n ): CardInstrument | undefined {\n if (!instrument) {\n return;\n }\n\n const { id, paymentSource } = instrument;\n const { brand, expiry, lastDigits } = paymentSource.card;\n\n const [expiryYear, expiryMonth] = expiry.split('-');\n\n return {\n bigpayToken: id,\n brand,\n defaultInstrument: false,\n expiryMonth,\n expiryYear,\n iin: '',\n last4: lastDigits,\n method: methodId,\n provider: methodId,\n trustedShippingAddress: false,\n untrustedShippingCardVerificationMode: UntrustedShippingCardVerificationType.CVV,\n type: 'card',\n };\n }\n\n /**\n *\n * Braintree Fastlane shipping address change through Fastlane external popup\n *\n */\n private async _handleBraintreeFastlaneShippingAddressChange(): Promise<\n CustomerAddress | undefined\n > {\n const state = this._store.getState();\n const countries = state.countries.getCountries() || [];\n const braintreeFastlane = await this._braintreeIntegrationService.getBraintreeFastlane();\n\n const { selectionChanged, selectedAddress } =\n await braintreeFastlane.profile.showShippingAddressSelector();\n\n if (selectionChanged) {\n const state = this._store.getState();\n const shipping = state.shippingAddress.getShippingAddressesOrThrow();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreeFastlaneCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n const shippingAddress = this._mapPayPalToBcAddress(\n selectedAddress,\n countries,\n selectedAddress.phoneNumber,\n shipping[0].customFields,\n );\n\n if (shippingAddress) {\n const paymentProviderCustomerAddresses = this._filterAddresses([\n shippingAddress,\n ...(braintreeFastlaneCustomer.addresses || []),\n ]);\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n ...braintreeFastlaneCustomer,\n addresses: paymentProviderCustomerAddresses,\n }),\n );\n\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n\n return shippingAddress;\n }\n }\n\n return undefined;\n }\n\n /**\n *\n * This method is responsible for filtering BT Fastlane addresses if they are the same\n * and returns an array of addresses to use them for shipping and/or billing address selections\n * so the customer will be able to use addresses from BT Fastlane in checkout flow\n *\n */\n private _filterAddresses(addresses: Array): CustomerAddress[] {\n return addresses.reduce(\n (customerAddresses: CustomerAddress[], currentAddress: CustomerAddress | undefined) => {\n if (!currentAddress) {\n return customerAddresses;\n }\n\n const sameAddressInTheArray = customerAddresses.some((customerAddress) =>\n this._isEqualAddresses(customerAddress, currentAddress),\n );\n\n return sameAddressInTheArray\n ? customerAddresses\n : [...customerAddresses, currentAddress];\n },\n [],\n );\n }\n\n private _isEqualAddresses(\n firstAddress: CustomerAddress,\n secondAddress: CustomerAddress,\n ): boolean {\n return isEqual(this._normalizeAddress(firstAddress), this._normalizeAddress(secondAddress));\n }\n\n private async _shouldUseBraintreeFastlaneShippingComponent(methodId: string): Promise {\n const state = this._store.getState();\n const paymentProviderCustomer = state.paymentProviderCustomer.getPaymentProviderCustomer();\n const braintreePaymentProviderCustomer = isBraintreeAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n // Info: to avoid loading payment method we should check for values\n // that does not require api calls first\n if (\n !!braintreePaymentProviderCustomer &&\n braintreePaymentProviderCustomer !== BraintreeFastlaneAuthenticationState.CANCELED\n ) {\n const paymentMethod = await this._getBraintreePaymentMethodOrThrow(methodId);\n\n return !!paymentMethod?.initializationData?.isFastlaneEnabled;\n }\n\n return false;\n }\n\n private async _getBraintreePaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n const newState = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n return newState.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n return paymentMethod;\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class DefaultShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","import { CustomerAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getFastlaneStyles,\n isPayPalCommerceAcceleratedCheckoutCustomer,\n isPayPalFastlaneCustomer,\n PayPalCommerceFastlaneUtils,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalFastlaneAuthenticationState,\n PayPalFastlaneStylesOption,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { PaymentProviderCustomerActionCreator } from '../../../payment-provider-customer';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class PayPalCommerceFastlaneShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentProviderCustomerActionCreator: PaymentProviderCustomerActionCreator,\n private _paypalCommerceSdk: PayPalCommerceSdk,\n private _paypalCommerceFastlaneUtils: PayPalCommerceFastlaneUtils,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { methodId, paypalcommercefastlane } = options || {};\n const { onPayPalFastlaneAddressChange, styles } = paypalcommercefastlane || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const customer = state.customer.getCustomerOrThrow();\n\n if (!customer?.isGuest) {\n return Promise.resolve(this._store.getState());\n }\n\n try {\n if (this._shouldAuthenticateUserWithFastlane()) {\n await this._initializePayPalSdk(methodId, styles);\n await this._authenticateUserWithFastlaneOtp(methodId);\n }\n\n if (\n typeof onPayPalFastlaneAddressChange === 'function' &&\n this._shouldUsePayPalFastlaneShippingComponent()\n ) {\n await this._initializePayPalSdk(methodId, styles);\n onPayPalFastlaneAddressChange(() => this._handlePayPalShippingAddressChange());\n }\n } catch (error) {\n // Info: we should not throw any error here to avoid customer stuck on\n // shipping step due to the payment provider custom flow\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private async _getPayPalPaymentMethodOrThrow(\n methodId: string,\n ): Promise> {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n const newState = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n return newState.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n return paymentMethod;\n }\n\n private _getPayPalCustomerAuthenticationState(): string | undefined {\n const state = this._store.getState();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomerOrThrow();\n const paypalCommercePaymentProviderCustomer = isPayPalCommerceAcceleratedCheckoutCustomer(\n paymentProviderCustomer,\n )\n ? paymentProviderCustomer\n : {};\n\n return paypalCommercePaymentProviderCustomer.authenticationState;\n }\n\n private _shouldAuthenticateUserWithFastlane(): boolean {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const paypalConnectSessionId = this._paypalCommerceFastlaneUtils.getStorageSessionId();\n\n const customerAuthenticationState = this._getPayPalCustomerAuthenticationState();\n\n return !customerAuthenticationState && paypalConnectSessionId === cart.id;\n }\n\n private _shouldUsePayPalFastlaneShippingComponent(): boolean {\n const customerAuthenticationState = this._getPayPalCustomerAuthenticationState();\n\n return (\n !!customerAuthenticationState &&\n customerAuthenticationState !== PayPalFastlaneAuthenticationState.CANCELED\n );\n }\n\n private async _initializePayPalSdk(\n methodId: string,\n styles?: PayPalFastlaneStylesOption,\n ): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n\n const paymentMethod = await this._getPayPalPaymentMethodOrThrow(methodId);\n const { isDeveloperModeApplicable, isFastlaneStylingEnabled } =\n paymentMethod?.initializationData || {};\n const isTestModeEnabled = !!isDeveloperModeApplicable;\n\n const fastlaneStyles = getFastlaneStyles(\n isFastlaneStylingEnabled ? paymentMethod?.initializationData?.fastlaneStyles : {},\n styles,\n );\n\n const paypalFastlaneSdk = await this._paypalCommerceSdk.getPayPalFastlaneSdk(\n paymentMethod,\n cart.currency.code,\n cart.id,\n );\n\n await this._paypalCommerceFastlaneUtils.initializePayPalFastlane(\n paypalFastlaneSdk,\n isTestModeEnabled,\n fastlaneStyles,\n );\n }\n\n private async _authenticateUserWithFastlaneOtp(methodId: string): Promise {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const customerEmail = state.customer.getCustomer()?.email;\n const billingAddressEmail = state.billingAddress.getBillingAddress()?.email;\n const email = customerEmail || billingAddressEmail || '';\n\n const { customerContextId } = await this._paypalCommerceFastlaneUtils.lookupCustomerOrThrow(\n email,\n );\n\n const authenticationResult =\n await this._paypalCommerceFastlaneUtils.triggerAuthenticationFlowOrThrow(\n customerContextId,\n );\n\n const { authenticationState, addresses, billingAddress, shippingAddress, instruments } =\n this._paypalCommerceFastlaneUtils.mapPayPalFastlaneProfileToBcCustomerData(\n methodId,\n authenticationResult,\n );\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n authenticationState,\n addresses,\n instruments,\n }),\n );\n\n const isAuthenticationFlowCanceled =\n authenticationResult.authenticationState === PayPalFastlaneAuthenticationState.CANCELED;\n\n this._paypalCommerceFastlaneUtils.updateStorageSessionId(\n isAuthenticationFlowCanceled,\n cart.id,\n );\n\n if (billingAddress) {\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress({\n ...billingAddress,\n id: String(billingAddress.id),\n }),\n );\n }\n\n if (shippingAddress && cart.lineItems.physicalItems.length > 0) {\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n }\n }\n\n /**\n *\n * PayPal Fastlane shipping address change through Fastlane external popup\n *\n */\n private async _handlePayPalShippingAddressChange(): Promise {\n const paypalFastlaneSdk = this._paypalCommerceFastlaneUtils.getPayPalFastlaneOrThrow();\n\n const { selectionChanged, selectedAddress } =\n await paypalFastlaneSdk.profile.showShippingAddressSelector();\n\n if (selectionChanged) {\n const state = this._store.getState();\n const shipping = state.shippingAddress.getShippingAddressesOrThrow();\n const paymentProviderCustomer =\n state.paymentProviderCustomer.getPaymentProviderCustomer();\n const paypalFastlaneCustomer = isPayPalFastlaneCustomer(paymentProviderCustomer)\n ? paymentProviderCustomer\n : {};\n\n const shippingAddress = this._paypalCommerceFastlaneUtils.mapPayPalToBcAddress(\n selectedAddress.address,\n selectedAddress.name,\n selectedAddress.phoneNumber,\n shipping[0].customFields,\n );\n\n const paymentProviderCustomerAddresses =\n this._paypalCommerceFastlaneUtils.filterAddresses([\n shippingAddress,\n ...(paypalFastlaneCustomer.addresses || []),\n ]);\n\n await this._store.dispatch(\n this._paymentProviderCustomerActionCreator.updatePaymentProviderCustomer({\n ...paypalFastlaneCustomer,\n addresses: paymentProviderCustomerAddresses,\n }),\n );\n\n await this._store.dispatch(\n this._consignmentActionCreator.updateAddress(shippingAddress),\n );\n\n return shippingAddress;\n }\n\n return undefined;\n }\n}\n","import { CustomFont, PaymentIntent, StripeConfigurationOptions } from '../stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n };\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport interface AddressOptions {\n city?: string;\n country?: string;\n state?: string;\n postal_code?: string;\n line1?: string;\n line2?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postal_code: string;\n country: string;\n };\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): void;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n };\n rules?: {\n '.Input'?: {\n borderColor?: string;\n color?: string;\n boxShadow?: string;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\ninterface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n\nexport enum StripeUPEPaymentIntentStatus {\n REQUIRES_PAYMENT_METHOD = 'requires_payment_method',\n REQUIRES_CONFIRMATION = 'requires_confirmation',\n REQUIRES_ACTION = 'requires_action',\n PROCESSING = 'processing',\n SUCCEEDED = 'succeeded',\n CANCELED = 'canceled',\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n DisplayName,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class StripeUPEShippingStrategy implements ShippingStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const {\n container,\n gatewayId,\n methodId,\n onChangeShipping,\n getStyles,\n availableCountries,\n getStripeState,\n } = options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n if (\n !paymentMethod ||\n !paymentMethod.initializationData.stripePublishableKey ||\n !paymentMethod.clientToken\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions;\n const styles = getStyles && getStyles();\n\n const {\n form: { getShippingAddressFields },\n shippingAddress: { getShippingAddress },\n } = this._store.getState();\n\n const shippingFields = getShippingAddressFields([], '');\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {\n variables: {\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n };\n }\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n appearance,\n });\n\n const shipping = getShippingAddress();\n const shippingPhoneField = shippingFields.find((field) => field.name === 'phone');\n let option: StripeElementsCreateOptions = {\n mode: StripeFormMode.SHIPPING,\n allowedCountries: [availableCountries],\n fields: {\n phone: 'always',\n },\n validation: {\n phone: {\n required:\n shippingPhoneField && shippingPhoneField.required ? 'always' : 'never',\n },\n },\n display: {\n name: DisplayName.SPLIT,\n },\n };\n\n if (shipping) {\n const {\n stateOrProvinceCode,\n countryCode,\n lastName,\n firstName,\n phone,\n address1,\n address2,\n city,\n postalCode,\n } = shipping;\n const stripeState =\n stateOrProvinceCode && countryCode\n ? getStripeState(countryCode, stateOrProvinceCode)\n : stateOrProvinceCode;\n\n option = {\n ...option,\n defaultValues: {\n firstName,\n lastName,\n phone,\n address: {\n line1: address1,\n line2: address2,\n city,\n state: stripeState,\n postal_code: postalCode,\n country: countryCode,\n },\n },\n };\n }\n\n let shippingAddressElement = this._stripeElements.getElement(StripeElementType.SHIPPING);\n\n if (shippingAddressElement) {\n shippingAddressElement.destroy();\n }\n\n shippingAddressElement = this._stripeElements.create(StripeElementType.SHIPPING, option);\n\n shippingAddressElement.on('change', (event: StripeEventType) => {\n if (!('isNewAddress' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n if (event.complete || event.isNewAddress) {\n if (this.sendData) {\n clearTimeout(this.sendData);\n }\n\n this.sendData = setTimeout(() => {\n onChangeShipping({\n ...event,\n phoneFieldRequired: shippingPhoneField\n ? shippingPhoneField.required\n : false,\n });\n }, 1000);\n }\n });\n\n shippingAddressElement.mount(`#${container}`);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n /* The new shipping component by StripeLink has a small bug, when the component is unmounted,\n Stripe does not save the shipping, to solve this, we will leave it mounted,\n and once it is fixed will be unmounted again */\n\n // this._stripeElements?.getElement(StripeElementType.SHIPPING)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { SignInEmail } from './signin-email';\n\nexport enum SignInEmailActionType {\n SendSignInEmailRequested = 'SEND_SIGNIN_EMAIL_REQUESTED',\n SendSignInEmailSucceeded = 'SEND_SIGNIN_EMAIL_SUCCEEDED',\n SendSignInEmailFailed = 'SEND_SIGNIN_EMAIL_FAILED',\n}\nexport type SendSignInEmailAction =\n | SendSignInEmailRequestedAction\n | SendSignInEmailSucceededAction\n | SendSignInEmailFailedAction;\n\nexport interface SendSignInEmailRequestedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailRequested;\n}\n\nexport interface SendSignInEmailSucceededAction extends Action {\n type: SignInEmailActionType.SendSignInEmailSucceeded;\n}\n\nexport interface SendSignInEmailFailedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { SignInEmailRequestBody } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailRequestSender from './signin-email-request-sender';\n\nexport default class SignInEmailActionCreator {\n constructor(private _requestSender: SignInEmailRequestSender) {}\n\n sendSignInEmail(\n emailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SignInEmailActionType.SendSignInEmailRequested)),\n defer(async () => {\n const { body } = await this._requestSender.sendSignInEmail(emailRequest, options);\n\n return createAction(SignInEmailActionType.SendSignInEmailSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SignInEmailActionType.SendSignInEmailFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { SignInEmail, SignInEmailRequestBody } from './signin-email';\n\nexport default class SignInEmailRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n sendSignInEmail(\n { email, redirectUrl }: SignInEmailRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/login.php?action=passwordless_login';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: {\n email,\n redirect_url:\n redirectUrl || parseUrl(window.top ? window.top.location.href : '').pathname,\n },\n headers,\n timeout,\n });\n }\n}\n","import { toSingleLine } from '../utility';\n\nexport default class ErrorMessageTransformer {\n constructor(private _messageCustomizer: (type: TError) => string) {}\n\n transform(error: TError): TError {\n error.message = toSingleLine(this._messageCustomizer(error));\n\n return error;\n }\n}\n","export default function toSingleLine(input?: string) {\n if (!input) {\n return '';\n }\n\n return input\n .split(/(?:\\r\\n|\\n|\\r)/)\n .map((line) => line.replace(/^\\s+/gm, ''))\n .join(' ')\n .trim();\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable } from 'rxjs';\n\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { AddressRequestBody } from '../address';\nimport { BillingAddressActionCreator, BillingAddressRequestBody } from '../billing';\nimport { DataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorMessageTransformer } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator } from '../config';\nimport { CouponActionCreator, GiftCertificateActionCreator } from '../coupon';\nimport {\n CustomerAccountRequestBody,\n CustomerActionCreator,\n CustomerAddressRequestBody,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerRequestOptions,\n CustomerStrategyActionCreator,\n ExecutePaymentMethodCheckoutOptions,\n GuestCredentials,\n} from '../customer';\nimport {\n ExtensionActionCreator,\n ExtensionCommandMap,\n ExtensionEventBroadcaster,\n ExtensionMessenger,\n ExtensionRegion,\n} from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n PaymentInitializeOptions,\n PaymentMethodActionCreator,\n PaymentRequestOptions,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { InstrumentActionCreator } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentAssignmentRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n PickupOptionActionCreator,\n PickupOptionRequestBody,\n ShippingCountryActionCreator,\n ShippingInitializeOptions,\n ShippingRequestOptions,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestBody } from '../signin-email';\nimport { SpamProtectionActionCreator, SpamProtectionOptions } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\nimport { Subscriptions, SubscriptionsActionCreator } from '../subscription';\n\nimport { CheckoutRequestBody } from './checkout';\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutParams from './checkout-params';\nimport CheckoutSelectors from './checkout-selectors';\nimport CheckoutStore from './checkout-store';\nimport createCheckoutServiceErrorTransformer from './create-checkout-service-error-transformer';\n\n/**\n * Responsible for completing the checkout process for the current customer.\n *\n * This object can be used to collect all information that is required for\n * checkout, such as shipping and billing information. It can also be used to\n * retrieve the current checkout state and subscribe to its changes.\n */\n@bind\nexport default class CheckoutService {\n private _errorTransformer: ErrorMessageTransformer;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _storeProjection: DataStoreProjection,\n private _extensionMessenger: ExtensionMessenger,\n private _extensionEventBroadcaster: ExtensionEventBroadcaster,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _configActionCreator: ConfigActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _countryActionCreator: CountryActionCreator,\n private _couponActionCreator: CouponActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _errorActionCreator: ErrorActionCreator,\n private _giftCertificateActionCreator: GiftCertificateActionCreator,\n private _instrumentActionCreator: InstrumentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _pickupOptionActionCreator: PickupOptionActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n private _signInEmailActionCreator: SignInEmailActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _subscriptionsActionCreator: SubscriptionsActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n private _extensionActionCreator: ExtensionActionCreator,\n ) {\n this._errorTransformer = createCheckoutServiceErrorTransformer();\n }\n\n /**\n * Returns a snapshot of the current checkout state.\n *\n * The method returns a new instance every time there is a change in the\n * checkout state. You can query the state by calling any of its getter\n * methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.data.getOrder());\n * console.log(state.errors.getSubmitOrderError());\n * console.log(state.statuses.isSubmittingOrder());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutSelectors {\n return this._storeProjection.getState();\n }\n\n /**\n * Notifies all subscribers with the current state.\n *\n * When this method gets called, the subscribers get called regardless if\n * they have any filters applied.\n */\n notifyState(): void {\n this._storeProjection.notifyState();\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the checkout state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.data.getCart());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.data.getCart();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.data.getCart())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutSelectors) => void,\n ...filters: Array<(state: CheckoutSelectors) => any>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n /**\n * Loads the current checkout.\n *\n * This method can only be called if there is an active checkout. Also, it\n * can only retrieve data that belongs to the current customer. When it is\n * successfully executed, you can retrieve the data by calling\n * `CheckoutStoreSelector#getCheckout`.\n *\n * ```js\n * const state = await service.loadCheckout('0cfd6c06-57c3-4e29-8d7a-de55cc8a9052');\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param id - The identifier of the checkout to load, or the default checkout if not provided.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n loadCheckout(\n id?: string,\n options?: RequestOptions,\n ): Promise {\n return this._dispatch(\n id\n ? this._checkoutActionCreator.loadCheckout(id, options)\n : this._checkoutActionCreator.loadDefaultCheckout(options),\n );\n }\n\n /**\n * Updates specific properties of the current checkout.\n *\n * ```js\n * const state = await service.updateCheckout(checkout);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param payload - The checkout properties to be updated.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n updateCheckout(\n payload: CheckoutRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._checkoutActionCreator.updateCheckout(payload, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads an order by an id.\n *\n * The method can only retrieve an order if the order belongs to the current\n * customer. If it is successfully executed, the data can be retrieved by\n * calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.loadOrder(123);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param orderId - The identifier of the order to load.\n * @param options - Options for loading the order.\n * @returns A promise that resolves to the current state.\n */\n loadOrder(orderId: number, options?: RequestOptions): Promise {\n const loadCheckoutAction = this._orderActionCreator.loadOrder(orderId, options);\n const formFieldsAction = this._formFieldsActionCreator.loadFormFields(options);\n const loadConfigAction = this._configActionCreator.loadConfig(options);\n\n return Promise.all([\n this._dispatch(loadCheckoutAction),\n this._dispatch(loadConfigAction, { queueId: 'config' }),\n this._dispatch(formFieldsAction, { queueId: 'formFields' }),\n ]).then(() => this.getState());\n }\n\n /**\n * Submits an order, thereby completing a checkout process.\n *\n * Before you can submit an order, you must initialize the payment method\n * chosen by the customer by calling `CheckoutService#initializePayment`.\n *\n * ```js\n * await service.initializePayment({ methodId: 'braintree' });\n * await service.submitOrder({\n * payment: {\n * methodId: 'braintree',\n * paymentData: {\n * ccExpiry: { month: 10, year: 20 },\n * ccName: 'BigCommerce',\n * ccNumber: '4111111111111111',\n * ccCvv: 123,\n * },\n * },\n * });\n * ```\n *\n * You are not required to include `paymentData` if the order does not\n * require additional payment details. For example, the customer has already\n * entered their payment details on the cart page using one of the hosted\n * payment methods, such as PayPal. Or the customer has applied a gift\n * certificate that exceeds the grand total amount.\n *\n * If the order is submitted successfully, you can retrieve the newly\n * created order by calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.submitOrder(payload);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param payload - The request payload to submit for the current order.\n * @param options - Options for submitting the current order.\n * @returns A promise that resolves to the current state.\n */\n submitOrder(payload: OrderRequestBody, options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.execute(payload, options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Finalizes the submission process for an order.\n *\n * This method is only required for certain hosted payment methods that\n * require a customer to enter their credit card details on their website.\n * You need to call this method once the customer has redirected back to\n * checkout in order to complete the checkout process.\n *\n * If the method is called before order finalization is required or for a\n * payment method that does not require order finalization, an error will be\n * thrown. Conversely, if the method is called successfully, you should\n * immediately redirect the customer to the order confirmation page.\n *\n * ```js\n * try {\n * await service.finalizeOrderIfNeeded();\n *\n * window.location.assign('/order-confirmation');\n * } catch (error) {\n * if (error.type !== 'order_finalization_not_required') {\n * throw error;\n * }\n * }\n * ```\n *\n * @param options - Options for finalizing the current order.\n * @returns A promise that resolves to the current state.\n * @throws `OrderFinalizationNotRequiredError` error if order finalization\n * is not required for the current order at the time of execution.\n */\n finalizeOrderIfNeeded(options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.finalize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of payment methods available for checkout.\n *\n * If a customer enters their payment details before navigating to the\n * checkout page (i.e.: using PayPal checkout button on the cart page), only\n * one payment method will be available for the customer - the selected\n * payment method. Otherwise, by default, all payment methods configured by\n * the merchant will be available for the customer.\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethods();\n *\n * console.log(state.data.getPaymentMethods());\n * ```\n *\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethods(options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethods(options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a list of payment methods for given ids.\n *\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethodsById(['applepay']);\n *\n * console.log(state.data.getPaymentMethodOrThrow('applepay'));\n * ```\n *\n * @param methodIds - The identifier for the payment methods to load.\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethodByIds(\n methodIds: string[],\n options?: RequestOptions,\n ): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethodsById(methodIds, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a payment method by an id.\n *\n * This method does not work with multi-option payment providers. Due to its\n * limitation, it is deprecated and will be removed in the future.\n *\n * @deprecated\n * @internal\n * @param methodId - The identifier for the payment method to load.\n * @param options - Options for loading the payment method.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethod(methodId: string, options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethod(methodId, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Initializes the payment step of a checkout process.\n *\n * Before a payment method can accept payment details, it must first be\n * initialized. Some payment methods require you to provide additional\n * initialization options. For example, you can provide an element ID for\n * Amazon Pay if you want users to be able to select a different payment\n * method by clicking on the element.\n *\n * ```js\n * await service.initializePayment({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editButtonId: 'edit-button',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializePayment(options: PaymentInitializeOptions): Promise {\n const action = this._paymentStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * De-initializes the payment step of a checkout process.\n *\n * The method should be called once you no longer require a payment method\n * to be initialized. It can perform any necessary clean-up behind the\n * scene, i.e.: remove DOM nodes or event handlers that are attached as a\n * result of payment initialization.\n *\n * ```js\n * await service.deinitializePayment({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializePayment(options: PaymentRequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of countries available for billing.\n *\n * Once you make a successful request, you will be able to retrieve the list\n * of countries by calling `CheckoutStoreSelector#getBillingCountries`.\n *\n * ```js\n * const state = await service.loadBillingCountries();\n *\n * console.log(state.data.getBillingCountries());\n * ```\n *\n * @param options - Options for loading the available billing countries.\n * @returns A promise that resolves to the current state.\n */\n loadBillingCountries(options?: RequestOptions): Promise {\n const action = this._countryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'billingCountries' });\n }\n\n /**\n * Loads a list of countries available for shipping.\n *\n * The list is determined based on the shipping zones configured by a\n * merchant. Once you make a successful call, you will be able to retrieve\n * the list of available shipping countries by calling\n * `CheckoutStoreSelector#getShippingCountries`.\n *\n * ```js\n * const state = await service.loadShippingCountries();\n *\n * console.log(state.data.getShippingCountries());\n * ```\n *\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadShippingCountries(options?: RequestOptions): Promise {\n const action = this._shippingCountryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'shippingCountries' });\n }\n\n /**\n * Loads a list of pickup options for a given criteria.\n *\n * ```js\n * const consignmentId = '1';\n * const searchArea = {\n * radius: {\n * value: 1.4,\n * unit: 'KM'\n * },\n * coordinates: {\n * latitude: 1.4,\n * longitude: 0\n * },\n * };\n * const state = await service.loadPickupOptions({ consignmentId, searchArea });\n *\n * console.log(state.data.getPickupOptions(consignmentId, searchArea));\n * ```\n *\n * @alpha\n * @param query - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadPickupOptions(query: PickupOptionRequestBody): Promise {\n const action = this._pickupOptionActionCreator.loadPickupOptions(query);\n\n return this._dispatch(action, { queueId: 'pickupOptions' });\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their billing address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getBillingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadBillingAddressFields();\n *\n * console.log(state.data.getBillingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the billing address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadBillingAddressFields(options?: RequestOptions): Promise {\n return this.loadBillingCountries(options);\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their shipping address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getShippingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadShippingAddressFields();\n *\n * console.log(state.data.getShippingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the shipping address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadShippingAddressFields(options?: RequestOptions): Promise {\n return this.loadShippingCountries(options);\n }\n\n /**\n * Initializes the sign-in step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, have their own sign-in flow. In\n * order to support them, this method must be called.\n *\n * ```js\n * await service.initializeCustomer({\n * methodId: 'amazonpay',\n * amazonpay: {\n * container: 'signInButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeCustomer(options?: CustomerInitializeOptions): Promise {\n const action = this._customerStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * De-initializes the sign-in step of a checkout process.\n *\n * It should be called once you no longer want to prompt customers to sign\n * in. It can perform any necessary clean-up behind the scene, i.e.: remove\n * DOM nodes or event handlers that are attached as a result of customer\n * initialization.\n *\n * ```js\n * await service.deinitializeCustomer({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Sends a email that contains a single-use sign-in link. When a valid links is clicked,\n * signs in the customer without requiring any password, redirecting them to the account page if no redirectUrl is provided.\n *\n *\n * ```js\n * checkoutService.sendSignInEmail({ email: 'foo@bar.com', redirectUrl: 'checkout' });\n * ```\n *\n * @param signInEmailRequest - The sign-in email request values.\n * @param options - Options for the send email request.\n * @returns A promise that resolves to the current state.\n */\n sendSignInEmail(\n signInEmailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._signInEmailActionCreator.sendSignInEmail(signInEmailRequest, options);\n\n return this._dispatch(action, { queueId: 'signInEmail' });\n }\n\n /**\n * Creates a customer account.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAccount({\n * email: 'foo@bar.com',\n * firstName: 'Foo',\n * lastName: 'Bar',\n * password: 'password',\n * acceptsMarketingEmails: true,\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccount` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAccount - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAccount(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createCustomer(customerAccount, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Creates a customer account address.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAddress({\n * firstName: 'Foo',\n * lastName: 'Bar',\n * address1: '55 Market St',\n * stateOrProvinceCode: 'CA',\n * countryCode: 'US',\n * postalCode: '90110',\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccountAddress` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAddress - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createAddress(customerAddress, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Updates the subscriptions associated to an email.\n *\n * @param subscriptions - The email and associated subscriptions to update.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Promise {\n const action = this._subscriptionsActionCreator.updateSubscriptions(subscriptions, options);\n\n return this._dispatch(action, { queueId: 'subscriptions' });\n }\n\n /**\n * Continues to check out as a guest.\n *\n * If your Checkout Settings allow it, your customers could continue the checkout as guests (without signing in).\n * If you have enabled the checkout setting \"Prompt existing accounts to sign in\", this information is\n * exposed as part of the [Customer](../interfaces/customer.md) object.\n *\n * Once they provide their email address, it will be stored as\n * part of their [billing address](../interfaces/billingaddress.md).\n *\n * @param credentials - The guest credentials to use, with optional subscriptions.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): Promise {\n const action = this._billingAddressActionCreator.continueAsGuest(credentials, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Signs into a customer's registered account.\n *\n * Once the customer is signed in successfully, the checkout state will be\n * populated with information associated with the customer, such as their\n * saved addresses. You can call `CheckoutStoreSelector#getCustomer` to\n * retrieve the data.\n *\n * ```js\n * const state = await service.signInCustomer({\n * email: 'foo@bar.com',\n * password: 'password123',\n * });\n *\n * console.log(state.data.getCustomer());\n * ```\n *\n * @param credentials - The credentials to be used for signing in the customer.\n * @param options - Options for signing in the customer.\n * @returns A promise that resolves to the current state.\n */\n signInCustomer(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.signIn(credentials, options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Signs out the current customer if they are previously signed in.\n *\n * Once the customer is successfully signed out, the checkout state will be\n * reset automatically.\n *\n * ```js\n * const state = await service.signOutCustomer();\n *\n * // The returned object should not contain information about the previously signed-in customer.\n * console.log(state.data.getCustomer());\n * ```\n *\n * When a store has \"Allow customers to access their cart across multiple devices\" enabled, signing out\n * will remove the cart/checkout data from the current session. An error with type=\"checkout_not_available\" will be thrown.\n *\n * ```js\n * try {\n * await service.signOutCustomer();\n * } catch (error) {\n * if (error.type === 'checkout_not_available') {\n * window.top.location.assign('/');\n * }\n * }\n * ```\n *\n * @param options - Options for signing out the customer.\n * @returns A promise that resolves to the current state.\n */\n signOutCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.signOut(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Executes custom checkout of the priority payment method.\n *\n * Some payment methods, such as Bolt, can use their own checkout\n * with autofilled customers data, to make checkout passing process\n * easier and faster for customers with Bolt account.\n *\n * ```js\n * await service.executePaymentMethodCheckout({\n * methodId: 'bolt',\n * fallback: () => {},\n * });\n * ```\n *\n * @param options - Options for executing payment method checkout.\n * @returns A promise that resolves to the current state.\n */\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.executePaymentMethodCheckout(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Loads a list of shipping options available for checkout.\n *\n * Available shipping options can only be determined once a customer\n * provides their shipping address. If the method is executed successfully,\n * `CheckoutStoreSelector#getShippingOptions` can be called to retrieve the\n * list of shipping options.\n *\n * ```js\n * const state = await service.loadShippingOptions();\n *\n * console.log(state.data.getShippingOptions());\n * ```\n *\n * @param options - Options for loading the available shipping options.\n * @returns A promise that resolves to the current state.\n */\n loadShippingOptions(options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.loadShippingOptions(options);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the shipping step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, can provide shipping\n * information to be used for checkout. In order to support them, this\n * method must be called.\n *\n * ```js\n * await service.initializeShipping({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editAddressButtonId: 'changeAddressButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeShipping(options?: ShippingInitializeOptions): Promise {\n const action = this._shippingStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * De-initializes the shipping step of a checkout process.\n *\n * It should be called once you no longer need to collect shipping details.\n * It can perform any necessary clean-up behind the scene, i.e.: remove DOM\n * nodes or event handlers that are attached as a result of shipping\n * initialization.\n *\n * ```js\n * await service.deinitializeShipping({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeShipping(options?: ShippingRequestOptions): Promise {\n const action = this._shippingStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for the current address.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectShippingOption('address-id', 'shipping-option-id');\n *\n * console.log(state.data.getSelectedShippingOption());\n * ```\n *\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectShippingOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.selectOption(shippingOptionId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the shipping address for the current checkout.\n *\n * When a customer updates their shipping address for an order, they will\n * see an updated list of shipping options and the cost for each option,\n * unless no options are available. If the update is successful, you can\n * call `CheckoutStoreSelector#getShippingAddress` to retrieve the address.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateShippingAddress(address);\n *\n * console.log(state.data.getShippingAddress());\n * ```\n *\n * @param address - The address to be used for shipping.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateShippingAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.updateAddress(address, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Creates consignments given a list.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * When consignments are created, an updated list of shipping options will\n * become available for each consignment, unless no options are available.\n * If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve the updated list of\n * consignments.'\n *\n * Beware that if a consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.createConsignments(consignments);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignments - The list of consignments to be created.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.createConsignments(consignments, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Deletes a consignment\n *\n * ```js\n * const state = await service.deleteConsignment('55c96cda6f04c');\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The ID of the consignment to be deleted\n * @param options - Options for the consignment delete request\n * @returns A promise that resolves to the current state.\n */\n deleteConsignment(consignmentId: string, options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.deleteConsignment(consignmentId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates a specific consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#selectShippingOption`.\n *\n * When a shipping address for a consignment is updated, an updated list of\n * shipping options will become available for the consignment, unless no\n * options are available. If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve updated list of\n * consignments.\n *\n * Beware that if the updated consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateConsignment(consignment);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateConsignment(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that assigns items to be shipped to a specific address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and assigns the provided items. If no consignment matches the address, a new one\n * will be created.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n assignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.assignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that unassigns items from a specific shipping address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and unassigns the specified items. If the consignment ends up with no line items\n * after the unassignment, it will be deleted.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n unassignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.unassignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for a given consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectConsignmentShippingOption(consignmentId, optionId);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The identified of the consignment to be updated.\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectConsignmentShippingOption(\n consignmentId: string,\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateShippingOption(\n {\n id: consignmentId,\n shippingOptionId,\n },\n options,\n );\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the billing address for the current checkout.\n *\n * A customer must provide their billing address before they can proceed to\n * pay for their order.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateBillingAddress(address);\n *\n * console.log(state.data.getBillingAddress());\n * ```\n *\n * @param address - The address to be used for billing.\n * @param options - Options for updating the billing address.\n * @returns A promise that resolves to the current state.\n */\n updateBillingAddress(\n address: Partial,\n options: RequestOptions = {},\n ): Promise {\n const action = this._billingAddressActionCreator.updateAddress(address, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies or removes customer's store credit code to the current checkout.\n *\n * Once the store credit gets applied, the outstanding balance will be adjusted accordingly.\n *\n * ```js\n * const state = await service.applyStoreCredit(true);\n *\n * console.log(state.data.getCheckout().outstandingBalance);\n * ```\n *\n * @param options - Options for applying store credit.\n * @returns A promise that resolves to the current state.\n */\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n const action = this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a coupon code to the current checkout.\n *\n * Once the coupon code gets applied, the quote for the current checkout will\n * be adjusted accordingly. The same coupon code cannot be applied more than\n * once.\n *\n * ```js\n * await service.applyCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to apply to the current checkout.\n * @param options - Options for applying the coupon code.\n * @returns A promise that resolves to the current state.\n */\n applyCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.applyCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a coupon code from the current checkout.\n *\n * Once the coupon code gets removed, the quote for the current checkout will\n * be adjusted accordingly.\n *\n * ```js\n * await service.removeCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to remove from the current checkout.\n * @param options - Options for removing the coupon code.\n * @returns A promise that resolves to the current state.\n */\n removeCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.removeCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a gift certificate to the current checkout.\n *\n * Once the gift certificate gets applied, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.applyGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to apply to the current checkout.\n * @param options - Options for applying the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n applyGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.applyGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a gift certificate from an order.\n *\n * Once the gift certificate gets removed, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.removeGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to remove from the current checkout.\n * @param options - Options for removing the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n removeGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.removeGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads a list of payment instruments associated with a customer.\n *\n * Once the method has been called successfully, you can retrieve the list\n * of payment instruments by calling `CheckoutStoreSelector#getInstruments`.\n * If the customer does not have any payment instruments on record, i.e.:\n * credit card, you will get an empty list instead.\n *\n * ```js\n * const state = service.loadInstruments();\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n loadInstruments(): Promise {\n const action = this._instrumentActionCreator.loadInstruments();\n\n return this._dispatch(action);\n }\n\n /**\n * Deletes a payment instrument by an id.\n *\n * Once an instrument gets removed, it can no longer be retrieved using\n * `CheckoutStoreSelector#getInstruments`.\n *\n * ```js\n * const state = service.deleteInstrument('123');\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns A promise that resolves to the current state.\n */\n deleteInstrument(instrumentId: string): Promise {\n const action = this._instrumentActionCreator.deleteInstrument(instrumentId);\n\n return this._dispatch(action).then(() => this.loadInstruments());\n }\n\n /**\n * Clear errors that have been collected from previous calls.\n *\n * ```js\n * const state = await service.clearError(error);\n *\n * console.log(state.errors.getError());\n * ```\n *\n * @param error - Specific error object to clear\n * @returns A promise that resolves to the current state.\n */\n clearError(error: Error): Promise {\n const action = this._errorActionCreator.clearError(error);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the spam protection for order creation.\n *\n * Note: Use `CheckoutService#executeSpamCheck` instead.\n * You do not need to call this method before calling\n * `CheckoutService#executeSpamCheck`.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails.\n *\n * ```js\n * await service.initializeSpamProtection();\n * ```\n *\n * @param options - Options for initializing spam protection.\n * @returns A promise that resolves to the current state.\n * @deprecated - Use CheckoutService#executeSpamCheck instead.\n */\n initializeSpamProtection(options: SpamProtectionOptions): Promise {\n const action = this._spamProtectionActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Verifies whether the current checkout is created by a human.\n *\n * Note: this method will do the initialization, therefore you do not\n * need to call `CheckoutService#initializeSpamProtection`\n * before calling this method.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails. You should call this method before\n * `submitOrder` method is called (i.e.: when the shopper\n * first gets to the payment step).\n *\n * **Note**: You need to enable Google ReCAPTCHA bot protection in your Checkout Settings.\n *\n * ```js\n * await service.executeSpamCheck();\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n executeSpamCheck(): Promise {\n const action = this._spamProtectionActionCreator.verifyCheckoutSpamProtection();\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Loads a list of extensions available for checkout.\n *\n * ```js\n * const state = await service.loadExtensions();\n *\n * console.log(state.data.getExtensions());\n * ```\n *\n * @alpha\n * @param options - Options for loading the extensions that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadExtensions(options?: RequestOptions): Promise {\n const action = this._extensionActionCreator.loadExtensions(options);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Renders an extension for a checkout extension region.\n * Currently, only one extension is allowed per region.\n *\n * @alpha\n * @param container - The ID of a container which the extension should be inserted.\n * @param region - The name of an area where the extension should be presented.\n * @returns A promise that resolves to the current state.\n */\n async renderExtension(container: string, region: ExtensionRegion): Promise {\n const action = this._extensionActionCreator.renderExtension(container, region);\n const state = await this._dispatch(action, { queueId: 'extensions' });\n\n this._extensionEventBroadcaster.listen();\n\n return state;\n }\n\n /**\n * Manages the command handler for an extension.\n *\n * @alpha\n * @param extensionId - The ID of the extension sending the command.\n * @param command - The command to be handled.\n * @param handler - The handler function for the extension command.\n * @returns A function that, when called, will deregister the command handler.\n */\n handleExtensionCommand(\n extensionId: string,\n command: T,\n handler: (command: ExtensionCommandMap[T]) => void,\n ): () => void {\n return this._extensionMessenger.listen(extensionId, command, handler);\n }\n\n /**\n * Dispatches an action through the data store and returns the current state\n * once the action is dispatched.\n *\n * @param action - The action to dispatch.\n * @returns A promise that resolves to the current state.\n */\n private _dispatch(\n action: Action | Observable | ThunkAction,\n options?: { queueId?: string },\n ): Promise {\n return this._store\n .dispatch(action, options)\n .then(() => this.getState())\n .catch((error) => {\n throw this._errorTransformer.transform(error);\n });\n }\n}\n","import { ErrorMessageTransformer } from '../common/error';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../common/error/errors';\nimport { getEnvironment } from '../common/utility';\n\nexport type CheckoutServiceErrorType = MissingDataError | NotInitializedError;\nexport type CheckoutServiceErrorTransformer = ErrorMessageTransformer<\n CheckoutServiceErrorType | Error\n>;\n\nexport default function createCheckoutServiceErrorTransformer(\n isDevelopment: boolean = getEnvironment() === 'development',\n): CheckoutServiceErrorTransformer {\n return new ErrorMessageTransformer((error) => {\n if (!isDevelopment || !isCheckoutServiceError(error)) {\n return error.message;\n }\n\n switch (error.subtype || error.type) {\n case MissingDataErrorType.MissingConsignments:\n return `\n ${error.message}\n The data could be unavailable because no shipping address has been provided.\n To fix this, create a consignment or update the shipping address before performing\n the same action again.\n `;\n\n case MissingDataErrorType.MissingCart:\n case MissingDataErrorType.MissingCheckout:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \\`CheckoutService#loadCheckout\\`\n before performing the same action again.\n `;\n\n case MissingDataErrorType.MissingCheckoutConfig:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you need to make sure \\`CheckoutService\\` is initialized\n properly by calling \\`CheckoutService#loadCheckout\\` before performing any\n other actions.\n `;\n\n case MissingDataErrorType.MissingOrder:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server yet.\n To fix this issue, you can try calling \\`CheckoutService#loadOrder\\`\n before performing the same action again.\n `;\n\n case MissingDataErrorType.MissingOrderId:\n return `\n ${error.message}\n The data could be unavailable because no order has been created yet. You have\n to first create the order before you can perform the action.\n `;\n\n case MissingDataErrorType.MissingPaymentMethod:\n return `\n ${error.message}\n The data could be unavailable because it has not loaded from the server, or\n configured by the merchant yet. To fix the former issue, you can try calling\n \\`CheckoutService#loadPaymentMethods\\` before performing the same action again.\n `;\n\n case NotInitializedErrorType.CustomerNotInitialized:\n return `\n In order to initialize the customer step of checkout, you need to call\n \\`CheckoutService#initializeCustomer\\`. Afterwards, you should be able to\n submit customer details.\n `;\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return `\n ${error.message}\n In order to initialize the payment step of checkout, you need to call\n \\`CheckoutService#initializePayment\\`. Afterwards, you should be able to\n submit payment details.\n `;\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return `\n ${error.message}\n In order to initialize the shipping step of checkout, you need to call\n \\`CheckoutService#initializeShipping\\`. Afterwards, you should be able to\n submit shipping details.\n `;\n\n default:\n return error.message;\n }\n });\n}\n\nfunction isCheckoutServiceError(error: any): error is CheckoutServiceErrorType {\n return !!(error.subtype || error.type);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"reselect\");","import { memoize } from '@bigcommerce/memoize';\nimport { createSelector as defaultSelectorCreator } from 'reselect';\n\n/**\n * Decorate selector creators with the ability to memoize the return value of\n * their combiner if it is a function (which effectively works as a partially\n * applied combiner).\n */\nexport default function withMemoizedCombiner(\n creator: T,\n): T {\n return ((...args: any[]) => {\n const combiner = args.pop();\n\n // Reselect's default `createSelector` has many overloads. To avoid having\n // to redefine all of them, we're using `any` to bypass the typechecker.\n return (creator as any)(...args, (...combinerArgs: any[]) => {\n // Although there are many overloads, all of them have the last argument\n // as the combiner.\n const result = combiner(...combinerArgs);\n\n if (typeof result === 'function') {\n return memoize(result);\n }\n\n return result;\n });\n }) as T;\n}\n","import { createSelector as defaultSelectorCreator } from 'reselect';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\n/**\n * This is a decorated version of Reselect's default `createSelector` function.\n * If the return value of the combiner function is a function, it will create a\n * memorized version of that function and return it instead.\n */\nexport default withMemoizedCombiner(defaultSelectorCreator);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"shallowequal\");","import { createSelectorCreator, defaultMemoize } from 'reselect';\nimport shallowEqual from 'shallowequal';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\nconst createShallowEqualSelector = createSelectorCreator(defaultMemoize, (a: any, b: any) =>\n shallowEqual(a, b),\n);\n\nexport default withMemoizedCombiner(createShallowEqualSelector);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if there is an unexpected error and it is not possible to\n * recover from unless the shopper creates a new checkout session.\n */\nexport default class UnrecoverableError extends RequestError {\n constructor(response: Response, message?: string) {\n super(response, {\n message:\n message ||\n 'An unexpected error has occurred. The checkout process cannot continue as a result.',\n });\n\n this.name = 'UnrecoverableError';\n this.type = 'unrecoverable';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromInternalErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || body.detail || body.title || message,\n errors: errors.length\n ? errors.map((message) => ({ code: body.type, message }))\n : [{ code: body.type, message: body.detail || body.title }],\n });\n}\n\nfunction joinErrors(errors: string[]): string | undefined {\n return errors\n .reduce((result: string[], error) => {\n if (error) {\n return [...result, error];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\nimport { last } from 'lodash';\n\nimport {\n ErrorResponseBody,\n InternalErrorResponseBody,\n StorefrontErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n mapFromInternalErrorResponse,\n mapFromPaymentErrorResponse,\n mapFromStorefrontErrorResponse,\n RequestError,\n TimeoutError,\n} from './errors';\n\nexport default class RequestErrorFactory {\n private _factoryMethods: { [key: string]: ErrorFactoryMethod } = {};\n\n constructor() {\n this.register('default', (response, message) => new RequestError(response, { message }));\n this.register('internal', (response, message) =>\n mapFromInternalErrorResponse(response, message),\n );\n this.register('storefront', (response, message) =>\n mapFromStorefrontErrorResponse(response, message),\n );\n this.register('payment', (response, message) =>\n mapFromPaymentErrorResponse(response, message),\n );\n this.register('timeout', (response) => new TimeoutError(response));\n }\n\n register(type: string, factoryMethod: ErrorFactoryMethod): void {\n this._factoryMethods[type] = factoryMethod;\n }\n\n createError(response: Response, message?: string): RequestError {\n const factoryMethod =\n this._factoryMethods[this._getType(response)] || this._factoryMethods.default;\n\n return factoryMethod(response, message);\n }\n\n private _getType(response: Response): string {\n if (response.status === 0) {\n return 'timeout';\n }\n\n if (this._isStorefrontErrorResponseBody(response.body)) {\n return 'storefront';\n }\n\n if (this._isInternalErrorResponseBody(response.body)) {\n const internalType = last(response.body.type.split('/'));\n\n return internalType && this._factoryMethods[internalType] ? internalType : 'internal';\n }\n\n const error = last(response.body && response.body.errors);\n\n if (error && error.code && this._factoryMethods[error.code]) {\n return error.code;\n }\n\n return 'payment';\n }\n\n private _isStorefrontErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is StorefrontErrorResponseBody {\n const storefrontErrorResponse = errorResponse as StorefrontErrorResponseBody;\n\n return (\n !this._isInternalErrorResponseBody(errorResponse) &&\n typeof storefrontErrorResponse.title === 'string' &&\n typeof storefrontErrorResponse.type === 'string' &&\n typeof storefrontErrorResponse.status === 'number' &&\n typeof storefrontErrorResponse.detail === 'string'\n );\n }\n\n private _isInternalErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is InternalErrorResponseBody {\n const internalErrorResponse = errorResponse as InternalErrorResponseBody;\n\n return (\n typeof internalErrorResponse.errors === 'object' &&\n typeof internalErrorResponse.title === 'string' &&\n typeof internalErrorResponse.type === 'string' &&\n typeof internalErrorResponse.status === 'number'\n );\n }\n}\n\nexport type ErrorFactoryMethod = (response: Response, message?: string) => RequestError;\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromStorefrontErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n\n return new RequestError(response, {\n message: message || body.detail || body.title,\n errors: [\n {\n code: body.code || body.type,\n message: body.detail || body.title,\n },\n ],\n });\n}\n","import { isPlainObject, omitBy, transform } from 'lodash';\n\nexport default function omitDeep(\n object: any,\n predicate: (value: any, key: string) => boolean,\n): any {\n if (Array.isArray(object)) {\n return object.map((value) => omitDeep(value, predicate));\n }\n\n if (isPlainObject(object)) {\n return transform(\n omitBy(object, predicate),\n (result, value, key) => {\n result[key] = omitDeep(value, predicate);\n },\n {} as { [key: string]: any },\n );\n }\n\n return object;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { omitDeep } from '../utility';\n\nimport { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default function clearErrorReducer<\n TState extends { [key: string]: any },\n TAction extends Action,\n>(state: TState, action: TAction): TState | undefined {\n if (isClearErrorAction(action)) {\n return omitDeep(state, (value) => value === action.payload);\n }\n\n return state;\n}\n\nfunction isClearErrorAction(action: Action): action is ClearErrorAction {\n return action.type === ErrorActionType.ClearError;\n}\n","export interface CompareOptions {\n keyFilter?(key: string): boolean;\n}\n\nexport default function isEqual(objectA: any, objectB: any, options?: CompareOptions): boolean {\n if (objectA === objectB) {\n return true;\n }\n\n if (objectA && objectB && typeof objectA === 'object' && typeof objectB === 'object') {\n if (Array.isArray(objectA) && Array.isArray(objectB)) {\n return isArrayEqual(objectA, objectB, options);\n }\n\n if (Array.isArray(objectA) || Array.isArray(objectB)) {\n return false;\n }\n\n if (objectA instanceof Date && objectB instanceof Date) {\n return isDateEqual(objectA, objectB);\n }\n\n if (objectA instanceof Date || objectB instanceof Date) {\n return false;\n }\n\n if (objectA instanceof RegExp && objectB instanceof RegExp) {\n return isRegExpEqual(objectA, objectB);\n }\n\n if (objectA instanceof RegExp || objectB instanceof RegExp) {\n return false;\n }\n\n return isObjectEqual(objectA, objectB, options);\n }\n\n return objectA === objectB;\n}\n\nfunction isRegExpEqual(objectA: RegExp, objectB: RegExp): boolean {\n return objectA.toString() === objectB.toString();\n}\n\nfunction isDateEqual(objectA: Date, objectB: Date): boolean {\n return objectA.getTime() === objectB.getTime();\n}\n\nfunction isArrayEqual(objectA: any[], objectB: any[], options?: CompareOptions): boolean {\n if (objectA.length !== objectB.length) {\n return false;\n }\n\n for (let index = 0, length = objectA.length; index < length; index++) {\n if (!isEqual(objectA[index], objectB[index], options)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isObjectEqual(\n objectA: { [key: string]: any },\n objectB: { [key: string]: any },\n options?: CompareOptions,\n): boolean {\n const filter = options && options.keyFilter;\n const keysA = filter ? Object.keys(objectA).filter(filter) : Object.keys(objectA);\n const keysB = filter ? Object.keys(objectB).filter(filter) : Object.keys(objectB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let index = 0, length = keysA.length; index < length; index++) {\n const key = keysA[index];\n\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) {\n return false;\n }\n\n if (!isEqual(objectA[key], objectB[key], options)) {\n return false;\n }\n }\n\n return true;\n}\n","import isEqual from './is-equal';\n\n/**\n * Replace the current value with a new value if the former is different to the\n * latter.\n */\nexport default function replace(currentValue: T, newValue?: T): T {\n if (newValue === undefined || isEqual(currentValue, newValue)) {\n return currentValue;\n }\n\n return newValue;\n}\n","import isEqual from './is-equal';\n\n/**\n * Set a new value to an object under a key if the new value is different to the\n * current value of the key.\n */\nexport default function objectSet(\n object: T | undefined,\n key: K,\n value: T[K],\n): T {\n if (\n object &&\n Object.prototype.hasOwnProperty.call(object, key) &&\n isEqual(object[key], value)\n ) {\n return object;\n }\n\n return {\n ...(object as any),\n [key]: value,\n };\n}\n","import BillingAddress from './billing-address';\n\nexport default interface BillingAddressState {\n data?: BillingAddress;\n errors: BillingAddressErrorsState;\n statuses: BillingAddressStatusesState;\n}\n\nexport interface BillingAddressErrorsState {\n loadError?: Error;\n updateError?: Error;\n continueAsGuestError?: Error;\n}\n\nexport interface BillingAddressStatusesState {\n isLoading?: boolean;\n isUpdating?: boolean;\n isContinuingAsGuest?: boolean;\n}\n\nexport const DEFAULT_STATE: BillingAddressState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet, replace } from '../common/utility';\nimport { OrderAction } from '../order';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport BillingAddress from './billing-address';\nimport { BillingAddressAction, BillingAddressActionType } from './billing-address-actions';\nimport BillingAddressState, {\n BillingAddressErrorsState,\n BillingAddressStatusesState,\n DEFAULT_STATE,\n} from './billing-address-state';\n\nexport default function billingAddressReducer(\n state: BillingAddressState = DEFAULT_STATE,\n action: Action,\n): BillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: BillingAddress | undefined,\n action: CheckoutAction | BillingAddressAction | OrderAction,\n): BillingAddress | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: BillingAddressErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case BillingAddressActionType.ContinueAsGuestRequested:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(errors, 'continueAsGuestError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n return objectSet(errors, 'continueAsGuestError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: BillingAddressStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case BillingAddressActionType.ContinueAsGuestRequested:\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isContinuingAsGuest', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(statuses, 'isContinuingAsGuest', false);\n\n default:\n return statuses;\n }\n}\n","import { isArray } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\nimport replace from './replace';\n\nexport interface ArrayReplaceOptions {\n matchObject(objectA: any, objectB: any): boolean;\n}\n\nfunction arrayReplace(\n currentArray: T[] | undefined,\n newArray: T[],\n options?: ArrayReplaceOptions,\n): T[];\nfunction arrayReplace(\n currentArray: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): undefined;\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined;\n\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined {\n const { matchObject = (a: any, b: any) => a.id !== undefined && a.id === b.id } = options || {};\n\n // Return the new array if the current array does not exist\n if (!currentArray) {\n return newArray;\n }\n\n // If the new array does not exist, or the current array is strictly equal\n // to the new array, exit early and return the current array so that the\n // object reference doesn't change\n if (!newArray || currentArray === newArray) {\n return currentArray;\n }\n\n // Otherwise, try to replace the items of the current array with the new\n // array. If the item from the two arrays are the same, keep the current\n // one. Do it recursively until all arrays are replaced.\n let sameAsCurrentCount = 0;\n let sameAsNewCount = 0;\n\n const countSameAsReplaced = (replacedValue: T, currentValue: T, newValue: T): T => {\n sameAsCurrentCount += replacedValue === currentValue ? 1 : 0;\n sameAsNewCount += replacedValue === newValue ? 1 : 0;\n\n return replacedValue;\n };\n\n const result = newArray.map((newItem, index) => {\n const currentItem = currentArray && currentArray[index];\n\n if (isPlainObject(currentItem) && isPlainObject(newItem)) {\n if (matchObject(currentItem, newItem)) {\n return countSameAsReplaced(objectMerge(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }\n\n if (isArray(currentItem) && isArray(newItem)) {\n return countSameAsReplaced(arrayReplace(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }) as T[];\n\n // If all items in the result are identical to the current array, and the\n // current array and the new array have the same size, simply return the\n // current array instead of the result.\n if (\n sameAsCurrentCount === newArray.length &&\n currentArray &&\n currentArray.length === newArray.length\n ) {\n return currentArray;\n }\n\n // If all items in the result are identical to the new array, simply return\n // the new array.\n if (sameAsNewCount === newArray.length) {\n return newArray;\n }\n\n return result;\n}\n\nexport default arrayReplace;\n","import { isArray } from 'lodash';\n\nimport arrayReplace from './array-replace';\nimport isPlainObject from './is-plain-object';\nimport objectSet from './object-set';\n\nfunction objectMerge(currentObject: T, newObject?: Partial): T;\nfunction objectMerge(\n currentObject: T | undefined,\n newObject: Partial,\n): Partial;\nfunction objectMerge(currentObject?: T, newObject?: Partial): T | undefined;\n\nfunction objectMerge(\n currentObject?: T,\n newObject?: Partial,\n): T | Partial | undefined {\n if (!currentObject) {\n return newObject;\n }\n\n // If the new object does not exist but the current object does, or the new\n // object is strictly equal to the current object, return the current object\n if (!newObject || currentObject === newObject) {\n return currentObject;\n }\n\n // If both objects exist, but some values might be different, perform a merge.\n // Retain values that are equal and only replace them with the new values if\n // they are different.\n return (Object.keys(newObject) as Array).reduce((result, key) => {\n const currentValue = result[key];\n const newValue = newObject[key];\n\n if (isPlainObject(currentValue) && isPlainObject(newValue)) {\n return objectSet(result, key, objectMerge(currentValue, newValue));\n }\n\n if (isArray(currentValue) && isArray(newValue)) {\n return objectSet(result, key, arrayReplace(currentValue, newValue) as any);\n }\n\n return objectSet(result, key, newValue as any);\n }, currentObject);\n}\n\nexport default objectMerge;\n","import Cart from './cart';\n\nexport default interface CartState {\n data?: Cart;\n errors: CartErrorsState;\n statuses: CartStatusesState;\n}\n\nexport interface CartErrorsState {\n loadError?: Error;\n}\n\nexport interface CartStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CartState = {\n errors: {},\n statuses: {},\n};\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadPaymentMethodAction } from '../payment';\n\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport enum CheckoutButtonActionType {\n InitializeButtonFailed = 'INITIALIZE_BUTTON_FAILED',\n InitializeButtonRequested = 'INITIALIZE_BUTTON_REQUESTED',\n InitializeButtonSucceeded = 'INITIALIZE_BUTTON_SUCCEEDED',\n\n DeinitializeButtonFailed = 'DEINITIALIZE_BUTTON_FAILED',\n DeinitializeButtonRequested = 'DEINITIALIZE_BUTTON_REQUESTED',\n DeinitializeButtonSucceeded = 'DEINITIALIZE_BUTTON_SUCCEEDED',\n}\n\nexport type CheckoutButtonAction = InitializeButtonAction | DeinitializeButtonAction;\n\nexport type InitializeButtonAction =\n | InitializeButtonRequestedAction\n | InitializeButtonSucceededAction\n | InitializeButtonFailedAction\n | LoadPaymentMethodAction;\n\nexport type DeinitializeButtonAction =\n | DeinitializeButtonRequestedAction\n | DeinitializeButtonSucceededAction\n | DeinitializeButtonFailedAction;\n\nexport interface CheckoutButtonActionMeta {\n methodId: CheckoutButtonMethodType;\n}\n\nexport interface InitializeButtonActionMeta extends CheckoutButtonActionMeta {\n containerId: string;\n}\n\nexport interface InitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonRequested;\n}\n\nexport interface InitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonSucceeded;\n}\n\nexport interface InitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.InitializeButtonFailed;\n}\n\nexport interface DeinitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonRequested;\n}\n\nexport interface DeinitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonSucceeded;\n}\n\nexport interface DeinitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonFailed;\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Cart from './cart';\nimport CartState, { CartErrorsState, CartStatusesState, DEFAULT_STATE } from './cart-state';\n\nexport default function cartReducer(state: CartState = DEFAULT_STATE, action: Action): CartState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Cart | undefined,\n action:\n | BillingAddressAction\n | CheckoutAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction,\n): Cart | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectMerge(data, action.payload && action.payload.cart);\n\n default:\n return data;\n }\n}\n\nfunction statusesReducer(\n statuses: CartStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction,\n): CartStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n\nfunction errorsReducer(\n errors: CartErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction,\n): CartErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n","import { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonState {\n data: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonDataState | undefined;\n };\n errors: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonErrorsState | undefined;\n };\n statuses: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonStatusesState | undefined;\n };\n}\n\nexport interface CheckoutButtonDataState {\n initializedContainers: {\n [key: string]: boolean;\n };\n}\n\nexport interface CheckoutButtonErrorsState {\n initializeError?: Error;\n deinitializeError?: Error;\n}\n\nexport interface CheckoutButtonStatusesState {\n isInitializing?: boolean;\n isDeinitializing?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutButtonState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { CheckoutButtonAction, CheckoutButtonActionType } from './checkout-button-actions';\nimport CheckoutButtonState, {\n CheckoutButtonDataState,\n CheckoutButtonErrorsState,\n CheckoutButtonStatusesState,\n DEFAULT_STATE,\n} from './checkout-button-state';\n\nconst DEFAULT_DATA_STATE: CheckoutButtonDataState = { initializedContainers: {} };\nconst DEFAULT_ERROR_STATE: CheckoutButtonErrorsState = {};\nconst DEFAULT_STATUS_STATE: CheckoutButtonStatusesState = {};\n\nexport default function checkoutButtonReducer(\n state: CheckoutButtonState = DEFAULT_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n errors: combineReducers({\n [action.meta.methodId]: errorsReducer,\n }),\n statuses: combineReducers({\n [action.meta.methodId]: statusesReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutButtonDataState = DEFAULT_DATA_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonDataState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n if (!action.meta || !action.meta.containerId) {\n return data;\n }\n\n return objectMerge(data, {\n initializedContainers: {\n [action.meta.containerId]: true,\n },\n });\n\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(data, 'initializedContainers', {});\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CheckoutButtonErrorsState = DEFAULT_ERROR_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonErrorsState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(errors, 'initializeError', undefined);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n return objectSet(errors, 'initializeError', action.payload);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(errors, 'deinitializeError', undefined);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n return objectSet(errors, 'deinitializeError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutButtonStatusesState = DEFAULT_STATUS_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonStatusesState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n return objectSet(statuses, 'isInitializing', true);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(statuses, 'isInitializing', false);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n return objectSet(statuses, 'isDeinitializing', true);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(statuses, 'isDeinitializing', false);\n\n default:\n return statuses;\n }\n}\n","import Config from './config';\n\nexport default interface ConfigState {\n data?: Config;\n meta?: ConfigMetaState;\n errors: ConfigErrorsState;\n statuses: ConfigStatusesState;\n}\n\nexport interface ConfigMetaState {\n externalSource?: string;\n variantIdentificationToken?: string;\n host?: string;\n locale?: string;\n}\n\nexport interface ConfigErrorsState {\n loadError?: Error;\n}\n\nexport interface ConfigStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ConfigState = {\n meta: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Config from './config';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\nimport ConfigState, { ConfigErrorsState, ConfigStatusesState, DEFAULT_STATE } from './config-state';\n\nexport default function configReducer(\n state: ConfigState = DEFAULT_STATE,\n action: Action,\n): ConfigState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Config | undefined, action: LoadConfigAction): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConfigErrorsState = DEFAULT_STATE.errors,\n action: LoadConfigAction,\n): ConfigErrorsState {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ConfigActionType.LoadConfigFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConfigStatusesState = DEFAULT_STATE.statuses,\n action: LoadConfigAction,\n): ConfigStatusesState {\n switch (action.type) {\n case ConfigActionType.LoadConfigRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConfigActionType.LoadConfigSucceeded:\n case ConfigActionType.LoadConfigFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport Coupon from './coupon';\n\nexport default interface CouponState {\n data?: Coupon[];\n errors: CouponErrorsState;\n statuses: CouponStatusesState;\n}\n\nexport interface CouponErrorsState {\n applyCouponError?: RequestError;\n removeCouponError?: RequestError;\n}\n\nexport interface CouponStatusesState {\n isApplyingCoupon?: boolean;\n isRemovingCoupon?: boolean;\n}\n\nexport const DEFAULT_STATE: CouponState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Coupon from './coupon';\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport CouponState, { CouponErrorsState, CouponStatusesState, DEFAULT_STATE } from './coupon-state';\n\nexport default function couponReducer(\n state: CouponState = DEFAULT_STATE,\n action: Action,\n): CouponState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Coupon[] | undefined,\n action: CouponAction | CheckoutAction | OrderAction | ConsignmentAction,\n): Coupon[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return arrayReplace(data, action.payload && action.payload.coupons);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: CouponErrorsState = {}, action: CouponAction): CouponErrorsState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n case CouponActionType.ApplyCouponSucceeded:\n return objectSet(errors, 'applyCouponError', undefined);\n\n case CouponActionType.ApplyCouponFailed:\n return objectSet(errors, 'applyCouponError', action.payload);\n\n case CouponActionType.RemoveCouponRequested:\n case CouponActionType.RemoveCouponSucceeded:\n return objectSet(errors, 'removeCouponError', undefined);\n\n case CouponActionType.RemoveCouponFailed:\n return objectSet(errors, 'removeCouponError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CouponStatusesState = {},\n action: CouponAction,\n): CouponStatusesState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n return objectSet(statuses, 'isApplyingCoupon', true);\n\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.ApplyCouponFailed:\n return objectSet(statuses, 'isApplyingCoupon', false);\n\n case CouponActionType.RemoveCouponRequested:\n return objectSet(statuses, 'isRemovingCoupon', true);\n\n case CouponActionType.RemoveCouponSucceeded:\n case CouponActionType.RemoveCouponFailed:\n return objectSet(statuses, 'isRemovingCoupon', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport GiftCertificate from './gift-certificate';\n\nexport default interface GiftCertificateState {\n data?: GiftCertificate[];\n errors: GiftCertificateErrorsState;\n statuses: GiftCertificateStatusesState;\n}\n\nexport interface GiftCertificateErrorsState {\n applyGiftCertificateError?: RequestError;\n removeGiftCertificateError?: RequestError;\n}\n\nexport interface GiftCertificateStatusesState {\n isApplyingGiftCertificate?: boolean;\n isRemovingGiftCertificate?: boolean;\n}\n\nexport const DEFAULT_STATE: GiftCertificateState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport GiftCertificate from './gift-certificate';\nimport { GiftCertificateAction, GiftCertificateActionType } from './gift-certificate-actions';\nimport GiftCertificateState, {\n DEFAULT_STATE,\n GiftCertificateErrorsState,\n GiftCertificateStatusesState,\n} from './gift-certificate-state';\n\nexport default function giftCertificateReducer(\n state: GiftCertificateState = DEFAULT_STATE,\n action: Action,\n): GiftCertificateState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: GiftCertificate[] | undefined,\n action: CheckoutAction | GiftCertificateAction | ConsignmentAction | CouponAction,\n): GiftCertificate[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return arrayReplace(data, action.payload && action.payload.giftCertificates);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: GiftCertificateErrorsState = DEFAULT_STATE.errors,\n action: GiftCertificateAction,\n): GiftCertificateErrorsState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n return objectSet(errors, 'applyGiftCertificateError', undefined);\n\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(errors, 'applyGiftCertificateError', action.payload);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectSet(errors, 'removeGiftCertificateError', undefined);\n\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(errors, 'removeGiftCertificateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: GiftCertificateStatusesState = DEFAULT_STATE.statuses,\n action: GiftCertificateAction,\n): GiftCertificateStatusesState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n return objectSet(statuses, 'isApplyingGiftCertificate', true);\n\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(statuses, 'isApplyingGiftCertificate', false);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n return objectSet(statuses, 'isRemovingGiftCertificate', true);\n\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(statuses, 'isRemovingGiftCertificate', false);\n\n default:\n return statuses;\n }\n}\n","import Customer from './customer';\n\nexport default interface CustomerState {\n data?: Customer;\n statuses: CustomerStatusesState;\n errors: CustomerErrorsState;\n}\n\nexport interface CustomerErrorsState {\n createError?: Error;\n createAddressError?: Error;\n}\n\nexport interface CustomerStatusesState {\n isCreating?: boolean;\n isCreatingAddress?: boolean;\n}\n\nexport const DEFAULT_STATE: CustomerState = {\n errors: {},\n statuses: {},\n};\n","import { combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressActionType, ContinueAsGuestAction } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Customer from './customer';\nimport {\n CustomerAction,\n CustomerActionType,\n StripeLinkAuthenticatedAction,\n} from './customer-actions';\nimport CustomerState, {\n CustomerErrorsState,\n CustomerStatusesState,\n DEFAULT_STATE,\n} from './customer-state';\n\ntype ReducerActionType =\n | CheckoutAction\n | ContinueAsGuestAction\n | CustomerAction\n | StripeLinkAuthenticatedAction;\n\nexport default function customerReducer(\n state: CustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): CustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Customer | undefined, action: ReducerActionType): Customer | undefined {\n switch (action.type) {\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectMerge(data, action.payload && action.payload.customer);\n\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CustomerErrorsState = DEFAULT_STATE.errors,\n action: ReducerActionType,\n): CustomerErrorsState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case CustomerActionType.CreateCustomerFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(errors, 'createAddressError', undefined);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n return objectSet(errors, 'createAddressError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStatusesState = DEFAULT_STATE.statuses,\n action: ReducerActionType,\n): CustomerStatusesState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case CustomerActionType.CreateCustomerFailed:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(statuses, 'isCreating', false);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n return objectSet(statuses, 'isCreatingAddress', true);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(statuses, 'isCreatingAddress', false);\n\n default:\n return statuses;\n }\n}\n","export default interface CustomerStrategyState {\n data: CustomerStrategyDataState;\n errors: CustomerStrategyErrorsState;\n statuses: CustomerStrategyStatusesState;\n}\n\nexport interface CustomerStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface CustomerStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeErrors?: { [key: string]: Error };\n initializeMethodId?: string;\n signInError?: Error;\n signInMethodId?: string;\n signOutError?: Error;\n signOutMethodId?: string;\n executePaymentMethodCheckoutError?: Error;\n executePaymentMethodCheckoutMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface CustomerStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isSigningIn?: boolean;\n isSigningOut?: boolean;\n signInMethodId?: string;\n signOutMethodId?: string;\n isExecutingPaymentMethodCheckout?: boolean;\n executePaymentMethodCheckoutMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: CustomerStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { CustomerStrategyAction, CustomerStrategyActionType } from './customer-strategy-actions';\nimport CustomerStrategyState, {\n CustomerStrategyDataState,\n CustomerStrategyErrorsState,\n CustomerStrategyStatusesState,\n DEFAULT_STATE,\n} from './customer-strategy-state';\n\nexport default function customerStrategyReducer(\n state: CustomerStrategyState = DEFAULT_STATE,\n action: Action,\n): CustomerStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CustomerStrategyDataState = DEFAULT_STATE.data,\n action: CustomerStrategyAction,\n): CustomerStrategyDataState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CustomerStrategyErrorsState = DEFAULT_STATE.errors,\n action: CustomerStrategyAction,\n): CustomerStrategyErrorsState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeErrors: { ...errors.initializeErrors },\n initializeMethodId: errors.initializeMethodId\n ? errors.initializeMethodId\n : undefined,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeErrors: {\n ...errors.initializeErrors,\n [action.meta && action.meta.methodId]: action.payload,\n },\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(errors, {\n signInError: undefined,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n return objectMerge(errors, {\n signInError: action.payload,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(errors, {\n signOutError: undefined,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n return objectMerge(errors, {\n signOutError: action.payload,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: undefined,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: action.payload,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n case CustomerStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStrategyStatusesState = DEFAULT_STATE.statuses,\n action: CustomerStrategyAction,\n): CustomerStrategyStatusesState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n return objectMerge(statuses, {\n isSigningIn: true,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(statuses, {\n isSigningIn: false,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n return objectMerge(statuses, {\n isSigningOut: true,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(statuses, {\n isSigningOut: false,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: true,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: false,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFinished:\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { Extension } from './extension';\n\nexport interface ExtensionState {\n data?: Extension[];\n errors: ExtensionErrorsState;\n statuses: ExtensionStatusesState;\n}\n\nexport interface ExtensionErrorsState {\n loadError?: Error;\n renderError?: Error;\n}\n\nexport interface ExtensionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ExtensionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport { Extension } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport {\n DEFAULT_STATE,\n ExtensionErrorsState,\n ExtensionState,\n ExtensionStatusesState,\n} from './extension-state';\n\nexport function extensionReducer(\n state: ExtensionState = DEFAULT_STATE,\n action: Action,\n): ExtensionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Extension[] | undefined,\n action: ExtensionAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ExtensionErrorsState = DEFAULT_STATE.errors,\n action: ExtensionAction,\n): ExtensionErrorsState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n case ExtensionActionType.LoadExtensionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ExtensionActionType.RenderExtensionRequested:\n case ExtensionActionType.RenderExtensionSucceeded:\n return objectSet(errors, 'renderError', undefined);\n\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ExtensionActionType.RenderExtensionFailed:\n return objectSet(errors, 'renderError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ExtensionStatusesState = DEFAULT_STATE.statuses,\n action: ExtensionAction,\n): ExtensionStatusesState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ExtensionActionType.LoadExtensionsSucceeded:\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n errors: FormFieldsErrorState;\n statuses: FormFieldsStatusesState;\n}\n\nexport interface FormFieldsErrorState {\n loadError?: Error;\n}\n\nexport interface FormFieldsStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: FormFieldsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { FormFields } from './form-field';\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsState, {\n DEFAULT_STATE,\n FormFieldsErrorState,\n FormFieldsStatusesState,\n} from './form-fields-state';\n\nexport default function formFieldsReducer(\n state: FormFieldsState = DEFAULT_STATE,\n action: Action,\n): FormFieldsState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: FormFields | undefined,\n action: LoadFormFieldsAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: FormFieldsErrorState = DEFAULT_STATE.errors,\n action: LoadFormFieldsAction,\n): FormFieldsErrorState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: FormFieldsStatusesState = DEFAULT_STATE.statuses,\n action: LoadFormFieldsAction,\n): FormFieldsStatusesState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import Country from './country';\n\nexport default interface CountryState {\n data?: Country[];\n errors: CountryErrorsState;\n statuses: CountryStatusesState;\n}\n\nexport interface CountryErrorsState {\n loadError?: Error;\n}\n\nexport interface CountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport Country from './country';\nimport { CountryActionType, LoadCountriesAction } from './country-actions';\nimport CountryState, {\n CountryErrorsState,\n CountryStatusesState,\n DEFAULT_STATE,\n} from './country-state';\n\nexport default function countryReducer(\n state: CountryState = DEFAULT_STATE,\n action: Action,\n): CountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case CountryActionType.LoadCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CountryErrorsState = DEFAULT_STATE.errors,\n action: LoadCountriesAction,\n): CountryErrorsState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n case CountryActionType.LoadCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CountryActionType.LoadCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadCountriesAction,\n): CountryStatusesState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CountryActionType.LoadCountriesSucceeded:\n case CountryActionType.LoadCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport { InternalOrderMeta, InternalOrderPayment } from './internal-order';\nimport Order from './order';\n\nexport default interface OrderState {\n data?: OrderDataState;\n meta?: OrderMetaState;\n errors: OrderErrorsState;\n statuses: OrderStatusesState;\n}\n\nexport type OrderDataState = Omit;\n\nexport interface OrderMetaState extends InternalOrderMeta {\n token?: string;\n orderToken?: string;\n callbackUrl?: string;\n payment?: InternalOrderPayment;\n}\n\nexport interface OrderErrorsState {\n loadError?: Error;\n submitError?: Error;\n finalizeError?: Error;\n}\n\nexport interface OrderStatusesState {\n isLoading?: boolean;\n isSubmitting?: boolean;\n isFinalizing?: boolean;\n}\n\nexport const DEFAULT_STATE: OrderState = {\n errors: {},\n meta: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { OrderAction, OrderActionType } from './order-actions';\nimport OrderState, {\n DEFAULT_STATE,\n OrderDataState,\n OrderErrorsState,\n OrderMetaState,\n OrderStatusesState,\n} from './order-state';\n\nexport default function orderReducer(\n state: OrderState = DEFAULT_STATE,\n action: Action,\n): OrderState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderDataState | undefined,\n action: OrderAction,\n): OrderDataState | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n return objectMerge(\n data,\n omit(action.payload, ['billingAddress', 'coupons']),\n ) as OrderDataState;\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: OrderMetaState | undefined,\n action: OrderAction,\n): OrderMetaState | undefined {\n switch (action.type) {\n case OrderActionType.FinalizeOrderSucceeded:\n case OrderActionType.SubmitOrderSucceeded:\n return objectMerge(meta, {\n ...action.meta,\n callbackUrl: action.payload && action.payload.order.callbackUrl,\n orderToken: action.payload && action.payload.order.token,\n payment: action.payload && action.payload.order && action.payload.order.payment,\n });\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: OrderErrorsState = DEFAULT_STATE.errors,\n action: OrderAction,\n): OrderErrorsState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: OrderStatusesState = DEFAULT_STATE.statuses,\n action: OrderAction,\n): OrderStatusesState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Address } from '../address';\n\nexport interface OrderBillingAddress extends Address {\n email?: string;\n}\n\nexport default interface OrderBillingAddressState {\n data?: OrderBillingAddress;\n}\n\nexport const DEFAULT_STATE: OrderBillingAddressState = {};\n","import { Action, combineReducers } from '@bigcommerce/data-store';\n\nimport { replace } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default function orderBillingAddressReducer(\n state: OrderBillingAddressState = DEFAULT_STATE,\n action: Action,\n): OrderBillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderBillingAddress | undefined,\n action: OrderAction,\n): OrderBillingAddress | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { PaymentAction, PaymentActionType } from './payment-actions';\nimport PaymentResponseBody from './payment-response-body';\nimport PaymentState from './payment-state';\n\nexport default function paymentReducer(\n state: PaymentState = {},\n action: PaymentAction,\n): PaymentState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentResponseBody | undefined,\n action: PaymentAction,\n): PaymentResponseBody | undefined {\n switch (action.type) {\n case PaymentActionType.SubmitPaymentSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n","import PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport default interface PaymentMethodState {\n data?: PaymentMethod[];\n meta?: PaymentMethodMeta;\n errors: PaymentMethodErrorsState;\n statuses: PaymentMethodStatusesState;\n}\n\nexport interface PaymentMethodErrorsState {\n loadMethodId?: string;\n loadError?: Error;\n loadMethodError?: Error;\n}\n\nexport interface PaymentMethodStatusesState {\n loadMethodId?: string;\n isLoading?: boolean;\n isLoadingMethod?: boolean;\n}\n\nexport const DEFAULT_STATE: PaymentMethodState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, mergeOrPush, objectMerge, objectSet } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, {\n DEFAULT_STATE,\n PaymentMethodErrorsState,\n PaymentMethodStatusesState,\n} from './payment-method-state';\n\nexport default function paymentMethodReducer(\n state: PaymentMethodState = DEFAULT_STATE,\n action: Action,\n): PaymentMethodState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentMethod[] | undefined,\n action: PaymentMethodAction,\n): PaymentMethod[] | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return mergeOrPush(\n data || [],\n action.payload,\n action.payload && {\n id: action.payload.id,\n gateway: action.payload.gateway,\n },\n );\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return arrayReplace(data, action.payload, {\n matchObject: (methodA, methodB) =>\n methodA.id === methodB.id && methodA.gateway === methodB.gateway,\n });\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: PaymentMethodMeta | undefined,\n action: PaymentMethodAction,\n): PaymentMethodMeta | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: PaymentMethodErrorsState = DEFAULT_STATE.errors,\n action: PaymentMethodAction,\n): PaymentMethodErrorsState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return objectMerge(errors, {\n loadMethodId: undefined,\n loadMethodError: undefined,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(errors, {\n loadMethodId: action.meta.methodId,\n loadMethodError: action.payload,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentMethodStatusesState = DEFAULT_STATE.statuses,\n action: PaymentMethodAction,\n): PaymentMethodStatusesState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n return objectMerge(statuses, {\n isLoadingMethod: true,\n loadMethodId: action.meta.methodId,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(statuses, {\n isLoadingMethod: false,\n loadMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { findIndex, pick, pickBy, ValueKeyIteratee } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\n\n/**\n * Push an item to an array if it doesn't exist in the array. Otherwise, merge\n * with the existing item in the array. This function always returns a new array.\n */\nexport default function mergeOrPush(array: T[], item?: T, predicate?: ValueKeyIteratee): T[] {\n if (!item) {\n return array;\n }\n\n const defaultPredicate = pick(item, 'id');\n const derivedPredicate: any =\n typeof predicate === 'object' ? pickBy(predicate) : predicate || defaultPredicate;\n const index = findIndex(array, derivedPredicate);\n const newArray = [...array];\n\n if (index === -1) {\n newArray.push(item);\n } else {\n const existingItem = array[index];\n\n newArray[index] =\n isPlainObject(existingItem) && isPlainObject(item)\n ? objectMerge(existingItem, item)\n : item;\n }\n\n return newArray;\n}\n","export default interface PaymentStrategyState {\n data: PaymentStrategyDataState;\n errors: PaymentStrategyErrorsState;\n statuses: PaymentStrategyStatusesState;\n}\n\nexport interface PaymentStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface PaymentStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n executeError?: Error;\n executeMethodId?: string;\n finalizeError?: Error;\n finalizeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface PaymentStrategyStatusesState {\n deinitializeMethodId?: string;\n executeMethodId?: string;\n finalizeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isExecuting?: boolean;\n isFinalizing?: boolean;\n isInitializing?: boolean;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: PaymentStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentStrategyAction, PaymentStrategyActionType } from './payment-strategy-actions';\nimport PaymentStrategyState, {\n DEFAULT_STATE,\n PaymentStrategyDataState,\n PaymentStrategyErrorsState,\n PaymentStrategyStatusesState,\n} from './payment-strategy-state';\n\nexport default function paymentStrategyReducer(\n state: PaymentStrategyState = DEFAULT_STATE,\n action: Action,\n): PaymentStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentStrategyDataState = DEFAULT_STATE.data,\n action: PaymentStrategyAction,\n): PaymentStrategyDataState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: true,\n },\n });\n }\n\n break;\n }\n\n case PaymentStrategyActionType.DeinitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: false,\n },\n });\n }\n }\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: PaymentStrategyErrorsState = DEFAULT_STATE.errors,\n action: PaymentStrategyAction,\n): PaymentStrategyErrorsState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.InitializeFailed: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeRequested:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeFailed: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.ExecuteRequested:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(errors, {\n executeError: undefined,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n return objectMerge(errors, {\n executeError: action.payload,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(errors, {\n finalizeError: undefined,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n return objectMerge(errors, {\n finalizeError: action.payload,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n case PaymentStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentStrategyStatusesState = DEFAULT_STATE.statuses,\n action: PaymentStrategyAction,\n): PaymentStrategyStatusesState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.InitializeFailed:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeRequested: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeFailed:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteRequested:\n return objectMerge(statuses, {\n isExecuting: true,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(statuses, {\n isExecuting: false,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n return objectMerge(statuses, {\n isFinalizing: true,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(statuses, {\n isFinalizing: false,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFinished:\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { PaymentProviderCustomer } from './payment-provider-customer';\n\nexport default interface PaymentProviderCustomerState {\n data: PaymentProviderCustomer;\n}\n\nexport const DEFAULT_STATE = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport {\n PaymentProviderCustomerType,\n UpdatePaymentProviderCustomerAction,\n} from './payment-provider-customer-actions';\nimport PaymentProviderCustomerState, { DEFAULT_STATE } from './payment-provider-customer-state';\n\ntype ReducerActionType = UpdatePaymentProviderCustomerAction;\n\nexport default function paymentProviderCustomerReducer(\n state: PaymentProviderCustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): PaymentProviderCustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentProviderCustomer = DEFAULT_STATE.data,\n action: ReducerActionType,\n): PaymentProviderCustomer {\n switch (action.type) {\n case PaymentProviderCustomerType.UpdatePaymentProviderCustomer:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import PaymentInstrument, { VaultAccessToken } from './instrument';\n\nexport default interface InstrumentState {\n data?: PaymentInstrument[];\n meta?: InstrumentMeta;\n errors: InstrumentErrorState;\n statuses: InstrumentStatusState;\n}\n\nexport interface InstrumentErrorState {\n deleteError?: Error;\n failedInstrument?: string;\n loadError?: Error;\n vaultError?: Error;\n}\n\nexport interface InstrumentStatusState {\n isDeleting?: boolean;\n isLoading?: boolean;\n isVaulting?: boolean;\n deletingInstrument?: string;\n}\n\nexport type InstrumentMeta = VaultAccessToken;\n\nexport const DEFAULT_STATE = {\n data: [],\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../../common/utility';\n\nimport PaymentInstrument from './instrument';\nimport { InstrumentAction, InstrumentActionType } from './instrument-actions';\nimport InstrumentState, {\n DEFAULT_STATE,\n InstrumentErrorState,\n InstrumentMeta,\n InstrumentStatusState,\n} from './instrument-state';\n\nexport default function instrumentReducer(\n state: InstrumentState = DEFAULT_STATE,\n action: Action,\n): InstrumentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentInstrument[] = DEFAULT_STATE.data,\n action: InstrumentAction,\n): PaymentInstrument[] {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return arrayReplace(data, (action.payload && action.payload.vaultedInstruments) || []);\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: InstrumentMeta | undefined,\n action: InstrumentAction,\n): InstrumentMeta | undefined {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: InstrumentErrorState = DEFAULT_STATE.errors,\n action: InstrumentAction,\n): InstrumentErrorState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(errors, {\n deleteError: undefined,\n failedInstrument: undefined,\n });\n\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(errors, {\n deleteError: action.payload,\n failedInstrument: action.meta.instrumentId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: InstrumentStatusState = DEFAULT_STATE.statuses,\n action: InstrumentAction,\n): InstrumentStatusState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n return objectMerge(statuses, {\n isDeleting: true,\n deletingInstrument: action.meta.instrumentId,\n });\n\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case InstrumentActionType.DeleteInstrumentSucceeded:\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(statuses, {\n isDeleting: false,\n deletingInstrument: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { AmazonPayRemoteCheckout } from './methods';\n\nexport default interface RemoteCheckoutState {\n data: RemoteCheckoutStateData;\n}\n\nexport interface RemoteCheckoutStateData {\n amazon?: AmazonPayRemoteCheckout;\n}\n\nexport const DEFAULT_STATE: RemoteCheckoutState = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport RemoteCheckout from './remote-checkout';\nimport { RemoteCheckoutAction, RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default function remoteCheckoutReducer(\n state: RemoteCheckoutState = DEFAULT_STATE,\n action: RemoteCheckoutAction,\n): RemoteCheckoutState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: RemoteCheckout, action: RemoteCheckoutAction): RemoteCheckout {\n switch (action.type) {\n case RemoteCheckoutActionType.InitializeRemoteBillingSucceeded:\n return objectSet(data, 'billing' as any, action.payload && action.payload.billing);\n\n case RemoteCheckoutActionType.InitializeRemoteShippingSucceeded:\n return objectSet(data, 'shipping' as any, action.payload && action.payload.shipping);\n\n case RemoteCheckoutActionType.LoadRemoteSettingsSucceeded:\n return objectSet(data, 'settings', action.payload);\n\n case RemoteCheckoutActionType.UpdateRemoteCheckout:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import Consignment from './consignment';\n\nexport default interface ConsignmentState {\n data?: Consignment[];\n errors: ConsignmentErrorsState;\n statuses: ConsignmentStatusesState;\n}\n\nexport interface ConsignmentErrorsState {\n loadError?: Error;\n loadShippingOptionsError?: Error;\n createError?: Error;\n updateError: { [key: string]: Error | undefined };\n deleteError: { [key: string]: Error | undefined };\n updateShippingOptionError: { [key: string]: Error | undefined };\n}\n\nexport interface ConsignmentStatusesState {\n isLoading?: boolean;\n isLoadingShippingOptions?: boolean;\n isCreating?: boolean;\n isUpdating: { [key: string]: boolean };\n isDeleting: { [key: string]: boolean };\n isUpdatingShippingOption: { [key: string]: boolean };\n}\n\nexport const DEFAULT_STATE: ConsignmentState = {\n errors: {\n updateShippingOptionError: {},\n updateError: {},\n deleteError: {},\n },\n statuses: {\n isUpdating: {},\n isUpdatingShippingOption: {},\n isDeleting: {},\n },\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType } from '../coupon';\nimport { CustomerAction, CustomerActionType } from '../customer';\n\nimport Consignment from './consignment';\nimport { ConsignmentAction, ConsignmentActionType } from './consignment-actions';\nimport ConsignmentState, {\n ConsignmentErrorsState,\n ConsignmentStatusesState,\n DEFAULT_STATE,\n} from './consignment-state';\n\nexport default function consignmentReducer(\n state: ConsignmentState = DEFAULT_STATE,\n action: Action,\n): ConsignmentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Consignment[] | undefined,\n action: ConsignmentAction | CheckoutAction | CouponAction | CustomerAction,\n): Consignment[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n return arrayReplace(data, action.payload && action.payload.consignments);\n\n case CustomerActionType.SignOutCustomerSucceeded:\n return arrayReplace(data, []);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConsignmentErrorsState = DEFAULT_STATE.errors,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConsignmentStatusesState = DEFAULT_STATE.statuses,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(statuses, 'isLoadingShippingOptions', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(statuses, 'isLoadingShippingOptions', false);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(statuses, 'isCreating', false);\n\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n default:\n return statuses;\n }\n}\n","/**\n * Takes a nested object and flattens it.\n */\nexport default function objectFlatten(\n object: { [key: string]: any },\n parent?: string,\n): { [key: string]: any } {\n const flattened: { [key: string]: any } = {};\n\n Object.keys(object).forEach((key: string) => {\n const value = object[key];\n const keyString = parent ? `${parent}.${key}` : key;\n\n if (typeof value === 'object') {\n Object.assign(flattened, objectFlatten(value, keyString));\n } else {\n flattened[keyString] = value;\n }\n });\n\n return flattened;\n}\n","export default function objectWithSortedKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n const sortedKeys = keys.sort();\n\n const sortedArray = sortedKeys.reduce(\n (previous, current) => ({\n ...previous,\n [current]: object[current],\n }),\n {},\n );\n\n return sortedArray;\n}\n","import { PickupOptionQueryMap } from './pickup-option';\n\nexport default interface PickupOptionState {\n data?: PickupOptionQueryMap;\n errors: PickupOptionErrorsState;\n statuses: PickupOptionStatusesState;\n}\n\nexport interface PickupOptionErrorsState {\n loadError?: Error;\n}\n\nexport interface PickupOptionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: PickupOptionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectFlatten, objectSet, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionQueryMap } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionState, {\n DEFAULT_STATE,\n PickupOptionErrorsState,\n PickupOptionStatusesState,\n} from './pickup-option-state';\n\nexport default function pickupOptionReducer(\n state: PickupOptionState = DEFAULT_STATE,\n action: Action,\n): PickupOptionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PickupOptionQueryMap | undefined,\n action: LoadPickupOptionsAction,\n): PickupOptionQueryMap | undefined {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n if (action.meta) {\n const optionQuery = {\n consignmentId: action.meta.consignmentId,\n searchArea: action.meta.searchArea,\n };\n const flattenedMeta = objectFlatten(optionQuery);\n const sortedflattenedMeta = objectWithSortedKeys(flattenedMeta);\n const keyString = btoa(`${JSON.stringify(sortedflattenedMeta)}`);\n\n return objectSet(data, keyString, action.payload);\n }\n\n break;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: PickupOptionErrorsState = DEFAULT_STATE.errors, action: Action) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PickupOptionStatusesState = DEFAULT_STATE.statuses,\n action: Action,\n) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Country } from '../geography';\n\nexport default interface ShippingCountryState {\n data?: Country[];\n errors: ShippingCountryErrorsState;\n statuses: ShippingCountryStatusesState;\n}\n\nexport interface ShippingCountryErrorsState {\n loadError?: Error;\n}\n\nexport interface ShippingCountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ShippingCountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { Country } from '../geography';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryState, {\n DEFAULT_STATE,\n ShippingCountryErrorsState,\n ShippingCountryStatusesState,\n} from './shipping-country-state';\n\nexport default function shippingCountryReducer(\n state: ShippingCountryState = DEFAULT_STATE,\n action: Action,\n): ShippingCountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadShippingCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ShippingCountryErrorsState = DEFAULT_STATE.errors,\n action: LoadShippingCountriesAction,\n): ShippingCountryErrorsState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingCountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadShippingCountriesAction,\n): ShippingCountryStatusesState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","export default interface ShippingStrategyState {\n data: ShippingStrategyDataState;\n errors: ShippingStrategyErrorsState;\n statuses: ShippingStrategyStatusesState;\n}\n\nexport interface ShippingStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface ShippingStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n updateAddressError?: Error;\n updateAddressMethodId?: string;\n selectOptionError?: Error;\n selectOptionMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface ShippingStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isUpdatingAddress?: boolean;\n isSelectingOption?: boolean;\n updateAddressMethodId?: string;\n selectOptionMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: ShippingStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { ShippingStrategyAction, ShippingStrategyActionType } from './shipping-strategy-actions';\nimport ShippingStrategyState, {\n DEFAULT_STATE,\n ShippingStrategyDataState,\n ShippingStrategyErrorsState,\n ShippingStrategyStatusesState,\n} from './shipping-strategy-state';\n\nexport default function shippingStrategyReducer(\n state: ShippingStrategyState = DEFAULT_STATE,\n action: Action,\n): ShippingStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: ShippingStrategyDataState = DEFAULT_STATE.data,\n action: ShippingStrategyAction,\n): ShippingStrategyDataState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ShippingStrategyErrorsState = DEFAULT_STATE.errors,\n action: ShippingStrategyAction,\n): ShippingStrategyErrorsState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(errors, {\n updateAddressError: undefined,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n return objectMerge(errors, {\n updateAddressError: action.payload,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(errors, {\n selectOptionError: undefined,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n return objectMerge(errors, {\n selectOptionError: action.payload,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n case ShippingStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingStrategyStatusesState = DEFAULT_STATE.statuses,\n action: ShippingStrategyAction,\n): ShippingStrategyStatusesState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n return objectMerge(statuses, {\n isUpdatingAddress: true,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(statuses, {\n isUpdatingAddress: false,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n return objectMerge(statuses, {\n isSelectingOption: true,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(statuses, {\n isSelectingOption: false,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFinished:\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { SignInEmail } from './signin-email';\n\nexport default interface SignInEmailState {\n data?: SignInEmail;\n errors: SignInEmailErrorsState;\n statuses: SignInEmailStatusesState;\n}\n\nexport interface SignInEmailErrorsState {\n sendError?: Error;\n}\n\nexport interface SignInEmailStatusesState {\n isSending?: boolean;\n}\n\nexport const DEFAULT_STATE: SignInEmailState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { SignInEmail } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailState, {\n DEFAULT_STATE,\n SignInEmailErrorsState,\n SignInEmailStatusesState,\n} from './signin-email-state';\n\nexport default function signInEmailReducer(\n state: SignInEmailState = DEFAULT_STATE,\n action: Action,\n): SignInEmailState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: SignInEmail | undefined,\n action: SendSignInEmailAction,\n): SignInEmail | undefined {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: SignInEmailErrorsState = DEFAULT_STATE.errors,\n action: SendSignInEmailAction,\n): SignInEmailErrorsState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(errors, 'sendError', undefined);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n return objectSet(errors, 'sendError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SignInEmailStatusesState = DEFAULT_STATE.statuses,\n action: SendSignInEmailAction,\n): SignInEmailStatusesState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n return objectSet(statuses, 'isSending', true);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(statuses, 'isSending', false);\n\n default:\n return statuses;\n }\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditState, {\n StoreCreditErrorsState,\n StoreCreditStatusesState,\n} from './store-credit-state';\n\nconst DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n\nexport default function storeCreditReducer(\n state: StoreCreditState = DEFAULT_STATE,\n action: Action,\n): StoreCreditState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: StoreCreditErrorsState = DEFAULT_STATE.errors,\n action: StoreCreditAction,\n): StoreCreditErrorsState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n return objectSet(errors, 'applyError', undefined);\n\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(errors, 'applyError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: StoreCreditStatusesState = DEFAULT_STATE.statuses,\n action: StoreCreditAction,\n): StoreCreditStatusesState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n return objectSet(statuses, 'isApplying', true);\n\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(statuses, 'isApplying', false);\n\n default:\n return statuses;\n }\n}\n","export default interface SubscriptionsState {\n errors: SubscriptionsErrorsState;\n statuses: SubscriptionsStatusesState;\n}\n\nexport interface SubscriptionsErrorsState {\n updateError?: Error;\n}\n\nexport interface SubscriptionsStatusesState {\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: SubscriptionsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport SubscriptionsState, {\n DEFAULT_STATE,\n SubscriptionsErrorsState,\n SubscriptionsStatusesState,\n} from './subscriptions-state';\n\nexport default function subscriptionsReducer(\n state: SubscriptionsState = DEFAULT_STATE,\n action: Action,\n): SubscriptionsState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: SubscriptionsErrorsState = DEFAULT_STATE.errors,\n action: UpdateSubscriptionsAction,\n): SubscriptionsErrorsState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SubscriptionsStatusesState = DEFAULT_STATE.statuses,\n action: UpdateSubscriptionsAction,\n): SubscriptionsStatusesState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport Checkout from './checkout';\n\nexport default interface CheckoutState {\n data?: CheckoutDataState;\n errors: CheckoutErrorsState;\n statuses: CheckoutStatusesState;\n}\n\nexport type CheckoutDataState = Omit<\n Checkout,\n 'billingAddress' | 'cart' | 'consignments' | 'coupons' | 'giftCertificates'\n>;\n\nexport interface CheckoutErrorsState {\n loadError?: Error;\n updateError?: Error;\n}\n\nexport interface CheckoutStatusesState {\n isExecutingSpamCheck?: boolean;\n isLoading?: boolean;\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\nimport { SpamProtectionAction, SpamProtectionActionType } from '../spam-protection';\nimport { StoreCreditAction, StoreCreditActionType } from '../store-credit';\n\nimport { CheckoutAction, CheckoutActionType } from './checkout-actions';\nimport CheckoutState, {\n CheckoutDataState,\n CheckoutErrorsState,\n CheckoutStatusesState,\n DEFAULT_STATE,\n} from './checkout-state';\n\nexport default function checkoutReducer(\n state: CheckoutState = DEFAULT_STATE,\n action: Action,\n): CheckoutState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutDataState | undefined,\n action:\n | CheckoutAction\n | BillingAddressAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction\n | OrderAction\n | SpamProtectionAction\n | StoreCreditAction,\n): CheckoutDataState | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case SpamProtectionActionType.VerifyCheckoutSucceeded:\n return objectMerge(\n data,\n omit(action.payload, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\n\n case OrderActionType.SubmitOrderSucceeded:\n return objectSet(data, 'orderId', action.payload && action.payload.order.orderId);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CheckoutErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | OrderAction,\n): CheckoutErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | OrderAction | SpamProtectionAction,\n): CheckoutStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case SpamProtectionActionType.ExecuteRequested:\n return objectSet(statuses, 'isExecutingSpamCheck', true);\n\n case SpamProtectionActionType.ExecuteFailed:\n case SpamProtectionActionType.ExecuteSucceeded:\n return objectSet(statuses, 'isExecutingSpamCheck', false);\n\n default:\n return statuses;\n }\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import { deepFreeze } from '@bigcommerce/data-store';\n\n// tslint:disable-next-line:ban-types\ntype FunctionProperties = { [K in keyof T]: T[K] extends Function ? T[K] : never };\n\nexport default function createFreezeProxy(target: T): T {\n return createProxy(\n target,\n (target, name) =>\n (...args: any[]) =>\n deepFreeze(target[name].call(target, ...args)),\n );\n}\n\nexport function createFreezeProxies(\n map: TMap,\n): TMap {\n return Object.keys(map).reduce((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {} as { [key: string]: T }) as TMap;\n}\n\nfunction createProxy(\n target: T,\n trap: (target: FunctionProperties, name: keyof FunctionProperties, proxy: T) => any,\n): T {\n const proxy = Object.create(target);\n\n traversePrototypeOf(target, (prototype) => {\n Object.getOwnPropertyNames(prototype).forEach((name) => {\n if (\n name === 'constructor' ||\n typeof proxy[name] !== 'function' ||\n name.charAt(0) === '_'\n ) {\n return;\n }\n\n proxy[name] = trap(target as FunctionProperties, name as keyof T, proxy);\n });\n });\n\n return proxy;\n}\n\nfunction traversePrototypeOf(target: object, iteratee: (prototype: object) => void): void {\n let prototype = Object.getPrototypeOf(target);\n\n while (prototype) {\n iteratee(prototype);\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n","import PaymentInstrument from './instrument';\n\ninterface SupportedInstruments {\n [key: string]: Pick;\n}\n\nconst supportedInstruments: SupportedInstruments = {\n 'mollie.credit_card': {\n provider: 'mollie',\n method: 'credit_card',\n },\n 'adyenv2.scheme': {\n provider: 'adyenv2',\n method: 'scheme',\n },\n 'adyenv3.scheme': {\n provider: 'adyenv3',\n method: 'scheme',\n },\n 'adyenv2.bcmc': {\n provider: 'adyenv2',\n method: 'bcmc',\n },\n 'adyenv2.ideal': {\n provider: 'adyenv2',\n method: 'ideal',\n },\n 'adyenv2.sepadirectdebit': {\n provider: 'adyenv2',\n method: 'sepadirectdebit',\n },\n 'adyenv2.directEbanking': {\n provider: 'adyenv2',\n method: 'directEbanking',\n },\n 'adyenv2.giropay': {\n provider: 'adyenv2',\n method: 'giropay',\n },\n barclays: {\n provider: 'barclays',\n method: 'credit_card',\n },\n braintree: {\n provider: 'braintree',\n method: 'credit_card',\n },\n braintreepaypal: {\n provider: 'braintree',\n method: 'paypal',\n },\n braintreeach: {\n provider: 'braintree',\n method: 'ach',\n },\n authorizenet: {\n provider: 'authorizenet',\n method: 'credit_card',\n },\n elavon: {\n provider: 'elavon',\n method: 'credit_card',\n },\n checkoutcom: {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.credit_card': {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.card': {\n provider: 'checkoutcom',\n method: 'card',\n },\n sagepay: {\n provider: 'sagepay',\n method: 'credit_card',\n },\n stripe: {\n provider: 'stripe',\n method: 'credit_card',\n },\n 'stripev3.card': {\n provider: 'stripev3',\n method: 'card',\n },\n 'stripeupe.card': {\n provider: 'stripeupe',\n method: 'card',\n },\n cybersource: {\n provider: 'cybersource',\n method: 'credit_card',\n },\n cybersourcev2: {\n provider: 'cybersourcev2',\n method: 'credit_card',\n },\n bnz: {\n provider: 'bnz',\n method: 'credit_card',\n },\n converge: {\n provider: 'converge',\n method: 'credit_card',\n },\n bluesnapv2: {\n provider: 'bluesnapv2',\n method: 'credit_card',\n },\n 'bluesnapdirect.credit_card': {\n provider: 'bluesnapdirect',\n method: 'credit_card',\n },\n 'bluesnapdirect.ecp': {\n provider: 'bluesnapdirect',\n method: 'ecp',\n },\n 'bluesnapdirect.sepa_direct_debit': {\n provider: 'bluesnapdirect',\n method: 'sepa_direct_debit',\n },\n orbital: {\n provider: 'orbital',\n method: 'credit_card',\n },\n paymetric: {\n provider: 'paymetric',\n method: 'credit_card',\n },\n bolt: {\n provider: 'bolt',\n method: 'credit_card',\n },\n 'barclaycard.credit_card': {\n provider: 'barclaycard',\n method: 'credit_card',\n },\n digitalriver: {\n provider: 'digitalriver',\n method: 'credit_card',\n },\n moneris: {\n provider: 'moneris',\n method: 'credit_card',\n },\n cba_mpgs: {\n provider: 'cba_mpgs',\n method: 'credit_card',\n },\n worldpayaccess: {\n provider: 'worldpayaccess',\n method: 'credit_card',\n },\n squarev2: {\n provider: 'squarev2',\n method: 'credit_card',\n },\n paypalcommercecreditcards: {\n provider: 'paypalcommerce',\n method: 'credit_card',\n },\n paypalcommerce: {\n provider: 'paypalcommerce',\n method: 'paypal',\n },\n tdonlinemart: {\n provider: 'tdonlinemart',\n method: 'credit_card',\n },\n};\n\nexport default supportedInstruments;\n","import { identity, isEqual, pickBy } from 'lodash';\n\nimport Address from './address';\n\nexport default function isAddressEqual(\n addressA: Partial
,\n addressB: Partial
,\n): boolean {\n return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial
): Partial
{\n return pickBy(\n {\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n address1: address.address1,\n address2: address.address2,\n city: address.city,\n stateOrProvince: address.stateOrProvince,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n phone: address.phone,\n customFields: address.customFields,\n },\n identity,\n );\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nexport default interface StoreCreditState {\n errors: StoreCreditErrorsState;\n statuses: StoreCreditStatusesState;\n}\n\nexport interface StoreCreditErrorsState {\n applyError?: RequestError;\n}\n\nexport interface StoreCreditStatusesState {\n isApplying?: boolean;\n}\n\nexport const DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n","import { createBillingAddressSelectorFactory } from '../billing';\nimport { createCartSelectorFactory } from '../cart';\nimport { createCheckoutButtonSelectorFactory } from '../checkout-buttons';\nimport { createFreezeProxies } from '../common/utility';\nimport { createConfigSelectorFactory } from '../config';\nimport { createCouponSelectorFactory, createGiftCertificateSelectorFactory } from '../coupon';\nimport { createCustomerSelectorFactory, createCustomerStrategySelectorFactory } from '../customer';\nimport { createExtensionSelectorFactory } from '../extension';\nimport { createFormSelectorFactory } from '../form';\nimport { createCountrySelectorFactory } from '../geography';\nimport { createOrderSelectorFactory } from '../order';\nimport { createOrderBillingAddressSelectorFactory } from '../order-billing-address';\nimport {\n createPaymentMethodSelectorFactory,\n createPaymentSelectorFactory,\n createPaymentStrategySelectorFactory,\n} from '../payment';\nimport { createPaymentProviderCustomerSelectorFactory } from '../payment-provider-customer';\nimport { createInstrumentSelectorFactory } from '../payment/instrument';\nimport { createRemoteCheckoutSelectorFactory } from '../remote-checkout';\nimport {\n createConsignmentSelectorFactory,\n createPickupOptionSelectorFactory,\n createShippingAddressSelectorFactory,\n createShippingCountrySelectorFactory,\n createShippingStrategySelectorFactory,\n} from '../shipping';\nimport { createSignInEmailSelectorFactory } from '../signin-email';\nimport { createStoreCreditSelectorFactory } from '../store-credit';\nimport { createSubscriptionsSelectorFactory } from '../subscription';\n\nimport { createCheckoutSelectorFactory } from './checkout-selector';\nimport { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type InternalCheckoutSelectorsFactory = (\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n) => InternalCheckoutSelectors;\n\nexport function createInternalCheckoutSelectorsFactory(): InternalCheckoutSelectorsFactory {\n const createBillingAddressSelector = createBillingAddressSelectorFactory();\n const createCartSelector = createCartSelectorFactory();\n const createCheckoutButtonSelector = createCheckoutButtonSelectorFactory();\n const createConfigSelector = createConfigSelectorFactory();\n const createCountrySelector = createCountrySelectorFactory();\n const createCouponSelector = createCouponSelectorFactory();\n const createCustomerSelector = createCustomerSelectorFactory();\n const createCustomerStrategySelector = createCustomerStrategySelectorFactory();\n const createGiftCertificateSelector = createGiftCertificateSelectorFactory();\n const createInstrumentSelector = createInstrumentSelectorFactory();\n const createFormSelector = createFormSelectorFactory();\n const createPaymentMethodSelector = createPaymentMethodSelectorFactory();\n const createPaymentStrategySelector = createPaymentStrategySelectorFactory();\n const createPickupOptionSelector = createPickupOptionSelectorFactory();\n const createPaymentProviderCustomerSelector = createPaymentProviderCustomerSelectorFactory();\n const createRemoteCheckoutSelector = createRemoteCheckoutSelectorFactory();\n const createShippingAddressSelector = createShippingAddressSelectorFactory();\n const createShippingCountrySelector = createShippingCountrySelectorFactory();\n const createShippingStrategySelector = createShippingStrategySelectorFactory();\n const createConsignmentSelector = createConsignmentSelectorFactory();\n const createCheckoutSelector = createCheckoutSelectorFactory();\n const createOrderSelector = createOrderSelectorFactory();\n const createOrderBillingAddressSelector = createOrderBillingAddressSelectorFactory();\n const createPaymentSelector = createPaymentSelectorFactory();\n const createStoreCreditSelector = createStoreCreditSelectorFactory();\n const createSubscriptionsSelector = createSubscriptionsSelectorFactory();\n const createSignInEmailSelector = createSignInEmailSelectorFactory();\n const createExtensionSelector = createExtensionSelectorFactory();\n\n return (state, options = {}) => {\n const billingAddress = createBillingAddressSelector(state.billingAddress);\n const cart = createCartSelector(state.cart);\n const checkoutButton = createCheckoutButtonSelector(state.checkoutButton);\n const countries = createCountrySelector(state.countries);\n const coupons = createCouponSelector(state.coupons);\n const customer = createCustomerSelector(state.customer);\n const customerStrategies = createCustomerStrategySelector(state.customerStrategies);\n const extensions = createExtensionSelector(state.extensions);\n const form = createFormSelector(state.formFields);\n const giftCertificates = createGiftCertificateSelector(state.giftCertificates);\n const instruments = createInstrumentSelector(state.instruments);\n const orderBillingAddress = createOrderBillingAddressSelector(state.orderBillingAddress);\n const paymentMethods = createPaymentMethodSelector(state.paymentMethods);\n const paymentProviderCustomer = createPaymentProviderCustomerSelector(\n state.paymentProviderCustomer,\n );\n const paymentStrategies = createPaymentStrategySelector(state.paymentStrategies);\n const pickupOptions = createPickupOptionSelector(state.pickupOptions);\n const remoteCheckout = createRemoteCheckoutSelector(state.remoteCheckout);\n const shippingAddress = createShippingAddressSelector(state.consignments);\n const shippingCountries = createShippingCountrySelector(state.shippingCountries);\n const shippingStrategies = createShippingStrategySelector(state.shippingStrategies);\n const subscriptions = createSubscriptionsSelector(state.subscriptions);\n const storeCredit = createStoreCreditSelector(state.storeCredit);\n const signInEmail = createSignInEmailSelector(state.signInEmail);\n\n // Compose selectors\n const consignments = createConsignmentSelector(state.consignments, cart);\n const checkout = createCheckoutSelector(\n state.checkout,\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n );\n const order = createOrderSelector(state.order, orderBillingAddress, coupons);\n const payment = createPaymentSelector(checkout, order);\n const config = createConfigSelector(state.config, state.formFields);\n\n const selectors = {\n billingAddress,\n cart,\n checkout,\n checkoutButton,\n config,\n consignments,\n countries,\n coupons,\n customer,\n customerStrategies,\n extensions,\n form,\n giftCertificates,\n instruments,\n order,\n orderBillingAddress,\n payment,\n paymentMethods,\n paymentProviderCustomer,\n paymentStrategies,\n pickupOptions,\n remoteCheckout,\n shippingAddress,\n shippingCountries,\n shippingStrategies,\n signInEmail,\n subscriptions,\n storeCredit,\n };\n\n return options.shouldWarnMutation ? createFreezeProxies(selectors) : selectors;\n };\n}\n\nexport default function createInternalCheckoutSelectors(\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n): InternalCheckoutSelectors {\n return createInternalCheckoutSelectorsFactory()(state, options);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport BillingAddress from './billing-address';\nimport BillingAddressState, { DEFAULT_STATE } from './billing-address-state';\n\nexport default interface BillingAddressSelector {\n getBillingAddress(): BillingAddress | undefined;\n getBillingAddressOrThrow(): BillingAddress;\n getUpdateError(): Error | undefined;\n getContinueAsGuestError(): Error | undefined;\n getLoadError(): Error | undefined;\n isUpdating(): boolean;\n isContinuingAsGuest(): boolean;\n isLoading(): boolean;\n}\n\nexport type BillingAddressSelectorFactory = (state: BillingAddressState) => BillingAddressSelector;\n\nexport function createBillingAddressSelectorFactory(): BillingAddressSelectorFactory {\n const getBillingAddress = createSelector(\n (state: BillingAddressState) => state.data,\n (data) => () => data,\n );\n\n const getBillingAddressOrThrow = createSelector(\n getBillingAddress,\n (getBillingAddress) => () => {\n return guard(\n getBillingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingBillingAddress),\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: BillingAddressState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const getContinueAsGuestError = createSelector(\n (state: BillingAddressState) => state.errors.continueAsGuestError,\n (error) => () => error,\n );\n\n const getLoadError = createSelector(\n (state: BillingAddressState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: BillingAddressState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n const isContinuingAsGuest = createSelector(\n (state: BillingAddressState) => !!state.statuses.isContinuingAsGuest,\n (status) => () => status,\n );\n\n const isLoading = createSelector(\n (state: BillingAddressState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: BillingAddressState = DEFAULT_STATE): BillingAddressSelector => {\n return {\n getBillingAddress: getBillingAddress(state),\n getBillingAddressOrThrow: getBillingAddressOrThrow(state),\n getUpdateError: getUpdateError(state),\n getContinueAsGuestError: getContinueAsGuestError(state),\n getLoadError: getLoadError(state),\n isUpdating: isUpdating(state),\n isContinuingAsGuest: isContinuingAsGuest(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoize, memoizeOne } from '@bigcommerce/memoize';\nimport { find, some, values } from 'lodash';\n\nimport { createSelector } from '../common/selector';\n\nimport CheckoutButtonState, { DEFAULT_STATE } from './checkout-button-state';\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonSelector {\n getState(): CheckoutButtonState;\n isInitializing(methodId?: CheckoutButtonMethodType): boolean;\n isInitialized(methodId: CheckoutButtonMethodType, containerId?: string): boolean;\n isDeinitializing(methodId?: CheckoutButtonMethodType): boolean;\n getInitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n getDeinitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n}\n\nexport type CheckoutButtonSelectorFactory = (state: CheckoutButtonState) => CheckoutButtonSelector;\n\nexport function createCheckoutButtonSelectorFactory(): CheckoutButtonSelectorFactory {\n const getState = createSelector(\n (state: CheckoutButtonState) => state,\n (state) => () => state,\n );\n\n const isInitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isInitializing) === true;\n }\n\n return some(statuses, { isInitializing: true });\n }),\n );\n\n const isInitialized = createSelector(\n (state: CheckoutButtonState) => state.data,\n (data) =>\n memoize((methodId: CheckoutButtonMethodType, containerId?: string) => {\n const method = data[methodId];\n\n if (!method) {\n return false;\n }\n\n if (!containerId) {\n return some(\n method.initializedContainers,\n (isInitialized) => isInitialized === true,\n );\n }\n\n return method.initializedContainers[containerId] === true;\n }),\n );\n\n const isDeinitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isDeinitializing) === true;\n }\n\n return some(statuses, { isDeinitializing: true });\n }),\n );\n\n const getInitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.initializeError));\n\n return method && method.initializeError;\n }),\n );\n\n const getDeinitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.deinitializeError));\n\n return method && method.deinitializeError;\n }),\n );\n\n return memoizeOne((state: CheckoutButtonState = DEFAULT_STATE): CheckoutButtonSelector => {\n return {\n getState: getState(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isDeinitializing: isDeinitializing(state),\n getInitializeError: getInitializeError(state),\n getDeinitializeError: getDeinitializeError(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport Coupon from './coupon';\nimport CouponState, { DEFAULT_STATE } from './coupon-state';\n\nexport default interface CouponSelector {\n getCoupons(): Coupon[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type CouponSelectorFactory = (state: CouponState) => CouponSelector;\n\nexport function createCouponSelectorFactory(): CouponSelectorFactory {\n const getCoupons = createSelector(\n (state: CouponState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: CouponState) => state.errors.removeCouponError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: CouponState) => state.errors.applyCouponError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: CouponState) => !!state.statuses.isApplyingCoupon,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: CouponState) => !!state.statuses.isRemovingCoupon,\n (status) => () => status,\n );\n\n return memoizeOne((state: CouponState = DEFAULT_STATE): CouponSelector => {\n return {\n getCoupons: getCoupons(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Customer from './customer';\nimport CustomerState, { DEFAULT_STATE } from './customer-state';\n\nexport default interface CustomerSelector {\n getCustomer(): Customer | undefined;\n getCustomerOrThrow(): Customer;\n getCreateAccountError(): Error | undefined;\n isCreatingCustomerAccount(): boolean;\n getCreateAddressError(): Error | undefined;\n isCreatingCustomerAddress(): boolean;\n}\n\nexport type CustomerSelectorFactory = (state: CustomerState) => CustomerSelector;\n\nexport function createCustomerSelectorFactory(): CustomerSelectorFactory {\n const getCustomer = createSelector(\n (state: CustomerState) => state.data,\n (customer) => () => customer,\n );\n\n const getCustomerOrThrow = createSelector(getCustomer, (getCustomer) => () => {\n return guard(\n getCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingCustomer),\n );\n });\n\n const getCreateAccountError = createSelector(\n (state: CustomerState) => state.errors.createError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAccount = createSelector(\n (state: CustomerState) => !!state.statuses.isCreating,\n (status) => () => status,\n );\n\n const getCreateAddressError = createSelector(\n (state: CustomerState) => state.errors.createAddressError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAddress = createSelector(\n (state: CustomerState) => !!state.statuses.isCreatingAddress,\n (status) => () => status,\n );\n\n return memoizeOne((state: CustomerState = DEFAULT_STATE): CustomerSelector => {\n return {\n getCustomer: getCustomer(state),\n getCustomerOrThrow: getCustomerOrThrow(state),\n getCreateAccountError: getCreateAccountError(state),\n isCreatingCustomerAccount: isCreatingCustomerAccount(state),\n getCreateAddressError: getCreateAddressError(state),\n isCreatingCustomerAddress: isCreatingCustomerAddress(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport { PaymentProviderCustomer } from './payment-provider-customer';\nimport PaymentProviderCustomerState, { DEFAULT_STATE } from './payment-provider-customer-state';\n\nexport default interface PaymentProviderCustomerSelector {\n getPaymentProviderCustomer(): PaymentProviderCustomer | undefined;\n getPaymentProviderCustomerOrThrow(): PaymentProviderCustomer;\n}\n\nexport type PaymentProviderCustomerSelectorFactory = (\n state: PaymentProviderCustomerState,\n) => PaymentProviderCustomerSelector;\n\nexport function createPaymentProviderCustomerSelectorFactory(): PaymentProviderCustomerSelectorFactory {\n const getPaymentProviderCustomer = createSelector(\n (state: PaymentProviderCustomerState) => state.data,\n (data) => () => data,\n );\n\n const getPaymentProviderCustomerOrThrow = createSelector(\n getPaymentProviderCustomer,\n (getPaymentProviderCustomer) => () => {\n return guard(\n getPaymentProviderCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentProviderCustomer),\n );\n },\n );\n\n return memoizeOne(\n (state: PaymentProviderCustomerState = DEFAULT_STATE): PaymentProviderCustomerSelector => {\n return {\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n getPaymentProviderCustomerOrThrow: getPaymentProviderCustomerOrThrow(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default interface RemoteCheckoutSelector {\n getCheckout(\n methodId: TMethodId,\n ): RemoteCheckoutStateData[TMethodId] | undefined;\n}\n\nexport type RemoteCheckoutSelectorFactory = (state: RemoteCheckoutState) => RemoteCheckoutSelector;\n\nexport function createRemoteCheckoutSelectorFactory(): RemoteCheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: RemoteCheckoutState) => state.data,\n (data) =>\n (methodId: TMethodId) => {\n return data[methodId];\n },\n );\n\n return memoizeOne((state: RemoteCheckoutState = DEFAULT_STATE): RemoteCheckoutSelector => {\n return {\n getCheckout: getCheckout(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { Address } from '../address';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\n\nexport default interface ShippingAddressSelector {\n getShippingAddress(): Address | undefined;\n getShippingAddressOrThrow(): Address;\n getShippingAddresses(): Address[];\n getShippingAddressesOrThrow(): Address[];\n}\n\nexport type ShippingAddressSelectorFactory = (state: ConsignmentState) => ShippingAddressSelector;\n\nexport function createShippingAddressSelectorFactory(): ShippingAddressSelectorFactory {\n const getShippingAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.shippingAddress;\n },\n );\n\n const getShippingAddressOrThrow = createSelector(\n getShippingAddress,\n (getShippingAddress) => () => {\n return guard(\n getShippingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n const getShippingAddresses = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignments = consignments?.filter(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignments\n ? shippingConsignments.map((consignment) => consignment.shippingAddress)\n : [];\n },\n );\n\n const getShippingAddressesOrThrow = createSelector(\n getShippingAddresses,\n (getShippingAddresses) => () => {\n return guard(\n getShippingAddresses(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n return memoizeOne((state: ConsignmentState = DEFAULT_STATE): ShippingAddressSelector => {\n return {\n getShippingAddress: getShippingAddress(state),\n getShippingAddressOrThrow: getShippingAddressOrThrow(state),\n getShippingAddresses: getShippingAddresses(state),\n getShippingAddressesOrThrow: getShippingAddressesOrThrow(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default interface OrderBillingAddressSelector {\n getOrderBillingAddress(): OrderBillingAddress | undefined;\n}\n\nexport type OrderBillingAddressSelectorFactory = (\n state: OrderBillingAddressState,\n) => OrderBillingAddressSelector;\n\nexport function createOrderBillingAddressSelectorFactory(): OrderBillingAddressSelectorFactory {\n const getOrderBillingAddress = createSelector(\n (state: OrderBillingAddressState) => state.data,\n (data) => () => data,\n );\n\n return memoizeOne(\n (state: OrderBillingAddressState = DEFAULT_STATE): OrderBillingAddressSelector => {\n return {\n getOrderBillingAddress: getOrderBillingAddress(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { CheckoutSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { GatewayOrderPayment, OrderSelector } from '../order';\n\nimport PaymentMethod from './payment-method';\nimport { HOSTED } from './payment-method-types';\nimport { ACKNOWLEDGE, FINALIZE } from './payment-status-types';\n\nexport default interface PaymentSelector {\n getPaymentId(): { providerId: string; gatewayId?: string } | undefined;\n getPaymentIdOrThrow(): { providerId: string; gatewayId?: string };\n getPaymentStatus(): string | undefined;\n getPaymentStatusOrThrow(): string;\n getPaymentToken(): string | undefined;\n getPaymentTokenOrThrow(): string;\n getPaymentRedirectUrl(): string | undefined;\n getPaymentRedirectUrlOrThrow(): string;\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n isPaymentDataSubmitted(paymentMethod?: PaymentMethod): boolean;\n}\n\nexport type PaymentSelectorFactory = (\n checkout: CheckoutSelector,\n order: OrderSelector,\n) => PaymentSelector;\n\ninterface PaymentSelectorDependencies {\n checkout: CheckoutSelector;\n order: OrderSelector;\n}\n\nexport function createPaymentSelectorFactory(): PaymentSelectorFactory {\n const getInternalPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.payment;\n },\n );\n\n const getGatewayPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrder,\n (getOrder) => () => {\n const order = getOrder();\n\n return find(\n order && order.payments,\n ({ providerId }) =>\n providerId !== 'giftcertificate' && providerId !== 'storecredit',\n ) as GatewayOrderPayment;\n },\n );\n\n const getHostedPayment = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getCheckout,\n (getCheckout) => () => {\n const checkout = getCheckout();\n\n return find(\n checkout && checkout.payments,\n ({ providerType }) => providerType === HOSTED,\n );\n },\n );\n\n const getPaymentId = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.id) {\n return {\n providerId: internalPayment.id,\n gatewayId: internalPayment.gateway,\n };\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment && payment.providerId) {\n return {\n providerId: payment.providerId,\n gatewayId: payment.gatewayId,\n };\n }\n },\n );\n\n const getPaymentIdOrThrow = createSelector(getPaymentId, (getPaymentId) => () => {\n return guard(\n getPaymentId(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentId),\n );\n });\n\n const getPaymentStatus = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.status) {\n return internalPayment.status.replace('PAYMENT_STATUS_', '');\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment) {\n return payment.detail.step;\n }\n },\n );\n\n const getPaymentStatusOrThrow = createSelector(getPaymentStatus, (getPaymentStatus) => () => {\n return guard(\n getPaymentStatus(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentStatus),\n );\n });\n\n const getPaymentToken = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.token;\n },\n );\n\n const getPaymentTokenOrThrow = createSelector(getPaymentToken, (getPaymentToken) => () => {\n return guard(\n getPaymentToken(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n });\n\n const getPaymentRedirectUrl = createSelector(getInternalPayment, (getInternalPayment) => () => {\n const payment = getInternalPayment();\n\n return payment && payment.redirectUrl;\n });\n\n const getPaymentRedirectUrlOrThrow = createSelector(\n getPaymentRedirectUrl,\n (getPaymentRedirectUrl) => () => {\n return guard(\n getPaymentRedirectUrl(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentRedirectUrl),\n );\n },\n );\n\n const isPaymentDataRequired = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getOutstandingBalance,\n (getOutstandingBalance) =>\n (useStoreCredit = false) => {\n const grandTotal = getOutstandingBalance(useStoreCredit);\n\n return grandTotal ? grandTotal > 0 : false;\n },\n );\n\n const isPaymentDataSubmitted = createSelector(\n getPaymentStatus,\n (getPaymentStatus) => (paymentMethod?: PaymentMethod) => {\n if (paymentMethod && paymentMethod.nonce) {\n return true;\n }\n\n return getPaymentStatus() === ACKNOWLEDGE || getPaymentStatus() === FINALIZE;\n },\n );\n\n return memoizeOne((checkout: CheckoutSelector, order: OrderSelector): PaymentSelector => {\n return {\n getPaymentId: getPaymentId({ checkout, order }),\n getPaymentIdOrThrow: getPaymentIdOrThrow({ checkout, order }),\n getPaymentStatus: getPaymentStatus({ checkout, order }),\n getPaymentStatusOrThrow: getPaymentStatusOrThrow({ checkout, order }),\n getPaymentToken: getPaymentToken({ checkout, order }),\n getPaymentTokenOrThrow: getPaymentTokenOrThrow({ checkout, order }),\n getPaymentRedirectUrl: getPaymentRedirectUrl({ checkout, order }),\n getPaymentRedirectUrlOrThrow: getPaymentRedirectUrlOrThrow({ checkout, order }),\n isPaymentDataRequired: isPaymentDataRequired({ checkout, order }),\n isPaymentDataSubmitted: isPaymentDataSubmitted({ checkout, order }),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { SignInEmail } from './signin-email';\nimport SignInEmailState, { DEFAULT_STATE } from './signin-email-state';\n\nexport default interface SignInEmailSelector {\n getEmail(): SignInEmail | undefined;\n getSendError(): Error | undefined;\n isSending(): boolean;\n}\n\nexport type SignInEmailSelectorFactory = (state: SignInEmailState) => SignInEmailSelector;\n\nexport function createSignInEmailSelectorFactory(): SignInEmailSelectorFactory {\n const getEmail = createSelector(\n (state: SignInEmailState) => state.data,\n (signInEmail) => () => signInEmail,\n );\n\n const getSendError = createSelector(\n (state: SignInEmailState) => state.errors.sendError,\n (error) => () => error,\n );\n\n const isSending = createSelector(\n (state: SignInEmailState) => !!state.statuses.isSending,\n (status) => () => status,\n );\n\n return memoizeOne((state: SignInEmailState = DEFAULT_STATE): SignInEmailSelector => {\n return {\n getEmail: getEmail(state),\n getSendError: getSendError(state),\n isSending: isSending(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Cart from './cart';\nimport CartState, { DEFAULT_STATE } from './cart-state';\n\nexport default interface CartSelector {\n getCart(): Cart | undefined;\n getCartOrThrow(): Cart;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CartSelectorFactory = (state: CartState) => CartSelector;\n\nexport function createCartSelectorFactory() {\n const getCart = createSelector(\n (state: CartState) => state.data,\n (cart) => () => cart,\n );\n\n const getCartOrThrow = createSelector(getCart, (getCart) => () => {\n return guard(getCart(), () => new MissingDataError(MissingDataErrorType.MissingCart));\n });\n\n const getLoadError = createSelector(\n (state: CartState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CartState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CartState = DEFAULT_STATE): CartSelector => {\n return {\n getCart: getCart(state),\n getCartOrThrow: getCartOrThrow(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { FormFieldsState } from '../form';\n\nimport Config, { ContextConfig, FlashMessage, FlashMessageType, StoreConfig } from './config';\nimport ConfigState, { DEFAULT_STATE } from './config-state';\n\nexport default interface ConfigSelector {\n getConfig(): Config | undefined;\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n getStoreConfig(): StoreConfig | undefined;\n getStoreConfigOrThrow(): StoreConfig;\n getContextConfig(): ContextConfig | undefined;\n getExternalSource(): string | undefined;\n getHost(): string | undefined;\n getLocale(): string | undefined;\n getVariantIdentificationToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ConfigSelectorFactory = (\n state: ConfigState,\n formState: FormFieldsState,\n) => ConfigSelector;\n\ninterface ConfigSelectorDependencies {\n formState: FormFieldsState;\n}\n\nexport function createConfigSelectorFactory(): ConfigSelectorFactory {\n const getConfig = createSelector(\n (state: ConfigState) => state.data,\n (data) => () => data,\n );\n\n const getFlashMessages = createSelector(\n (state: ConfigState) => state.data,\n (data) => (filterType?: FlashMessageType) => {\n if (!data) {\n return;\n }\n\n const { flashMessages } = data.context;\n\n if (!flashMessages) {\n return;\n }\n\n return filterType !== undefined\n ? flashMessages.filter(({ type }) => filterType === type)\n : flashMessages;\n },\n );\n\n const getStoreConfig = createSelector(\n (state: ConfigState) => state.data,\n (_: ConfigState, { formState }: ConfigSelectorDependencies) => formState && formState.data,\n (data, formFields) => () =>\n data && formFields\n ? {\n ...data.storeConfig,\n formFields,\n }\n : undefined,\n );\n\n const getStoreConfigOrThrow = createSelector(getStoreConfig, (getStoreConfig) => () => {\n return guard(\n getStoreConfig(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckoutConfig),\n );\n });\n\n const getContextConfig = createSelector(\n (state: ConfigState) => state.data && state.data.context,\n (data) => () => data,\n );\n\n const getExternalSource = createSelector(\n (state: ConfigState) => state.meta && state.meta.externalSource,\n (data) => () => data,\n );\n\n const getHost = createSelector(\n (state: ConfigState) => state.meta?.host,\n (data) => () => data,\n );\n\n const getLocale = createSelector(\n (state: ConfigState) => state.meta?.locale,\n (data) => () => data,\n );\n\n const getVariantIdentificationToken = createSelector(\n (state: ConfigState) => state.meta && state.meta.variantIdentificationToken,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ConfigState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ConfigState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (state: ConfigState = DEFAULT_STATE, formState: FormFieldsState): ConfigSelector => {\n return {\n getConfig: getConfig(state),\n getFlashMessages: getFlashMessages(state),\n getStoreConfig: getStoreConfig(state, { formState }),\n getStoreConfigOrThrow: getStoreConfigOrThrow(state, { formState }),\n getContextConfig: getContextConfig(state),\n getExternalSource: getExternalSource(state),\n getHost: getHost(state),\n getLocale: getLocale(state),\n getVariantIdentificationToken: getVariantIdentificationToken(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport Country from './country';\nimport CountryState, { DEFAULT_STATE } from './country-state';\n\nexport default interface CountrySelector {\n getCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CountrySelectorFactory = (state: CountryState) => CountrySelector;\n\nexport function createCountrySelectorFactory(): CountrySelectorFactory {\n const getCountries = createSelector(\n (state: CountryState) => state.data,\n (countries) => () => countries,\n );\n\n const getLoadError = createSelector(\n (state: CountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CountryState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CountryState = DEFAULT_STATE): CountrySelector => {\n return {\n getCountries: getCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport CustomerStrategyState, { DEFAULT_STATE } from './customer-strategy-state';\n\nexport default interface CustomerStrategySelector {\n getSignInError(methodId?: string): Error | undefined;\n getSignOutError(methodId?: string): Error | undefined;\n getExecutePaymentMethodCheckoutError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isSigningIn(methodId?: string): boolean;\n isSigningOut(methodId?: string): boolean;\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type CustomerStrategySelectorFactory = (\n state: CustomerStrategyState,\n) => CustomerStrategySelector;\n\nexport function createCustomerStrategySelectorFactory(): CustomerStrategySelectorFactory {\n const getSignInError = createSelector(\n (state: CustomerStrategyState) => state.errors.signInMethodId,\n (state: CustomerStrategyState) => state.errors.signInError,\n (signInMethodId, signInError) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return;\n }\n\n return signInError;\n },\n );\n\n const getSignOutError = createSelector(\n (state: CustomerStrategyState) => state.errors.signOutMethodId,\n (state: CustomerStrategyState) => state.errors.signOutError,\n (signOutMethodId, signOutError) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return;\n }\n\n return signOutError;\n },\n );\n\n const getExecutePaymentMethodCheckoutError = createSelector(\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutError,\n (executePaymentMethodCheckoutMethodId, executePaymentMethodCheckoutError) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return;\n }\n\n return executePaymentMethodCheckoutError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: CustomerStrategyState) => state.errors.initializeMethodId,\n (state: CustomerStrategyState) => state.errors.initializeErrors,\n (initializeMethodId, initializeErrors) => (methodId?: string) => {\n if (!initializeMethodId || !initializeErrors) {\n return;\n }\n\n if (methodId) {\n return initializeErrors[methodId];\n }\n\n return initializeErrors[initializeMethodId];\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: CustomerStrategyState) => state.errors.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isSigningIn = createSelector(\n (state: CustomerStrategyState) => state.statuses.signInMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningIn,\n (signInMethodId, isSigningIn) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningIn;\n },\n );\n\n const isSigningOut = createSelector(\n (state: CustomerStrategyState) => state.statuses.signOutMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningOut,\n (signOutMethodId, isSigningOut) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningOut;\n },\n );\n\n const isExecutingPaymentMethodCheckout = createSelector(\n (state: CustomerStrategyState) => state.statuses.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.statuses.isExecutingPaymentMethodCheckout,\n (executePaymentMethodCheckoutMethodId, isExecutingPaymentMethodCheckout) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return false;\n }\n\n return !!isExecutingPaymentMethodCheckout;\n },\n );\n\n const isInitializing = createSelector(\n (state: CustomerStrategyState) => state.statuses.initializeMethodId,\n (state: CustomerStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: CustomerStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: CustomerStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: CustomerStrategyState = DEFAULT_STATE): CustomerStrategySelector => {\n return {\n getSignInError: getSignInError(state),\n getSignOutError: getSignOutError(state),\n getExecutePaymentMethodCheckoutError: getExecutePaymentMethodCheckoutError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isSigningIn: isSigningIn(state),\n isSigningOut: isSigningOut(state),\n isExecutingPaymentMethodCheckout: isExecutingPaymentMethodCheckout(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport GiftCertificate from './gift-certificate';\nimport GiftCertificateState, { DEFAULT_STATE } from './gift-certificate-state';\n\nexport default interface GiftCertificateSelector {\n getGiftCertificates(): GiftCertificate[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type GiftCertificateSelectorFactory = (\n state: GiftCertificateState,\n) => GiftCertificateSelector;\n\nexport function createGiftCertificateSelectorFactory(): GiftCertificateSelectorFactory {\n const getGiftCertificates = createSelector(\n (state: GiftCertificateState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: GiftCertificateState) => state.errors.removeGiftCertificateError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: GiftCertificateState) => state.errors.applyGiftCertificateError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isApplyingGiftCertificate,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isRemovingGiftCertificate,\n (status) => () => status,\n );\n\n return memoizeOne((state: GiftCertificateState = DEFAULT_STATE): GiftCertificateSelector => {\n return {\n getGiftCertificates: getGiftCertificates(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { filter, flatMap, isMatch, values } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\nimport { createSelector } from '../../common/selector';\nimport { guard } from '../../common/utility';\nimport PaymentMethod from '../payment-method';\n\nimport PaymentInstrument, { CardInstrument } from './instrument';\nimport InstrumentState, { DEFAULT_STATE, InstrumentMeta } from './instrument-state';\nimport supportedInstruments from './supported-payment-instruments';\n\nexport default interface InstrumentSelector {\n getCardInstrument(instrumentId: string): CardInstrument | undefined;\n getCardInstrumentOrThrow(instrumentId: string): CardInstrument;\n getInstruments(): PaymentInstrument[] | undefined;\n getInstrumentsByPaymentMethod(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n getInstrumentsMeta(): InstrumentMeta | undefined;\n getLoadError(): Error | undefined;\n getDeleteError(instrumentId?: string): Error | undefined;\n isLoading(): boolean;\n isDeleting(instrumentId?: string): boolean;\n}\n\nexport type InstrumentSelectorFactory = (state: InstrumentState) => InstrumentSelector;\n\nexport function createInstrumentSelectorFactory(): InstrumentSelectorFactory {\n const getInstrumentsByPaymentMethod = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => (paymentMethod: PaymentMethod) => {\n if (!instruments) {\n return;\n }\n\n const paymentMethodKey = paymentMethod.gateway\n ? `${paymentMethod.gateway}.${paymentMethod.id}`\n : paymentMethod.id;\n\n const currentMethod = supportedInstruments[paymentMethodKey];\n\n if (!currentMethod) {\n return [];\n }\n\n return filter(instruments, currentMethod);\n },\n );\n\n const getCardInstrument = createSelector(\n (state: InstrumentState) => state.data,\n (instruments = []) =>\n (instrumentId: string) => {\n const cards = values(supportedInstruments);\n\n return instruments.find(\n (instrument): instrument is CardInstrument =>\n instrument.bigpayToken === instrumentId &&\n instrument.type === 'card' &&\n cards.some((card) => isMatch(instrument, card)),\n );\n },\n );\n\n const getCardInstrumentOrThrow = createSelector(\n getCardInstrument,\n (getCardInstrument) => (instrumentId: string) => {\n return guard(\n getCardInstrument(instrumentId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentInstrument),\n );\n },\n );\n\n const getInstruments = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => () => {\n if (!instruments) {\n return;\n }\n\n const allSupportedInstruments = flatMap(supportedInstruments, (supportedProvider) =>\n filter(\n instruments,\n (instrument: PaymentInstrument): instrument is PaymentInstrument => {\n return isMatch(instrument, supportedProvider);\n },\n ),\n );\n\n return allSupportedInstruments;\n },\n );\n\n const getInstrumentsMeta = createSelector(\n (state: InstrumentState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: InstrumentState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getDeleteError = createSelector(\n (state: InstrumentState) => state.errors.failedInstrument,\n (state: InstrumentState) => state.errors.deleteError,\n (failedInstrument, deleteError) => (instrumentId?: string) => {\n if (instrumentId && failedInstrument !== instrumentId) {\n return;\n }\n\n return deleteError;\n },\n );\n\n const isLoading = createSelector(\n (state: InstrumentState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isDeleting = createSelector(\n (state: InstrumentState) => state.statuses.deletingInstrument,\n (state: InstrumentState) => state.statuses.isDeleting,\n (deletingInstrument, isDeleting) => (instrumentId?: string) => {\n if (instrumentId && deletingInstrument !== instrumentId) {\n return false;\n }\n\n return !!isDeleting;\n },\n );\n\n return memoizeOne((state: InstrumentState = DEFAULT_STATE): InstrumentSelector => {\n return {\n getCardInstrument: getCardInstrument(state),\n getCardInstrumentOrThrow: getCardInstrumentOrThrow(state),\n getInstruments: getInstruments(state),\n getInstrumentsByPaymentMethod: getInstrumentsByPaymentMethod(state),\n getInstrumentsMeta: getInstrumentsMeta(state),\n getLoadError: getLoadError(state),\n getDeleteError: getDeleteError(state),\n isLoading: isLoading(state),\n isDeleting: isDeleting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport FormField from './form-field';\nimport FormFieldsState, { DEFAULT_STATE } from './form-fields-state';\n\nexport default interface FormSelector {\n getShippingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getBillingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getCustomerAccountFields(): FormField[];\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type FormSelectorFactory = (state: FormFieldsState) => FormSelector;\n\nexport function createFormSelectorFactory(): FormSelectorFactory {\n const getShippingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.shippingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getBillingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.billingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getCustomerAccountFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) => () => formFields ? formFields.customerAccount : [],\n );\n\n const getLoadError = createSelector(\n (state: FormFieldsState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: FormFieldsState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n function processField(\n field: FormField,\n countries: Country[],\n selectedCountry?: Country,\n ): FormField {\n if (field.name === 'countryCode') {\n return processCountry(field, countries, selectedCountry);\n }\n\n if (field.name === 'stateOrProvince') {\n return processProvince(field, selectedCountry);\n }\n\n if (field.name === 'postalCode') {\n return processsPostCode(field, selectedCountry);\n }\n\n return field;\n }\n\n function processCountry(\n field: FormField,\n countries: Country[] = [],\n country?: Country,\n ): FormField {\n if (!countries.length) {\n return field;\n }\n\n const { code = '' } = country || {};\n const items = countries.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n options: { items },\n default: code,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processProvince(field: FormField, country?: Country): FormField {\n const { subdivisions = [], requiresState } = country || {};\n\n if (!subdivisions.length) {\n return {\n ...field,\n required: requiresState == null ? false : requiresState,\n };\n }\n\n const items = subdivisions.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n name: 'stateOrProvinceCode',\n options: { items },\n required: requiresState == null ? true : requiresState,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processsPostCode(field: FormField, country?: Country): FormField {\n const { hasPostalCodes = [] } = country || {};\n\n if (hasPostalCodes === undefined) {\n return field;\n }\n\n return { ...field, required: Boolean(hasPostalCodes) };\n }\n\n return memoizeOne((state: FormFieldsState = DEFAULT_STATE): FormSelector => {\n return {\n getShippingAddressFields: getShippingAddressFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE } from './payment-method-state';\n\nexport default interface PaymentMethodSelector {\n getPaymentMethods(): PaymentMethod[] | undefined;\n getPaymentMethodsMeta(): PaymentMethodMeta | undefined;\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n getPaymentMethodOrThrow(methodId: string, gatewayId?: string): PaymentMethod;\n getLoadError(): Error | undefined;\n getLoadMethodError(methodId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingMethod(methodId?: string): boolean;\n}\n\nexport type PaymentMethodSelectorFactory = (state: PaymentMethodState) => PaymentMethodSelector;\n\nexport function createPaymentMethodSelectorFactory(): PaymentMethodSelectorFactory {\n const getPaymentMethods = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => () => paymentMethods,\n );\n\n const getPaymentMethodsMeta = createSelector(\n (state: PaymentMethodState) => state.meta,\n (meta) => () => meta,\n );\n\n const getPaymentMethod = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => (methodId: string, gatewayId?: string) => {\n return gatewayId\n ? find(paymentMethods, { id: methodId, gateway: gatewayId })\n : find(paymentMethods, { id: methodId });\n },\n );\n\n const getPaymentMethodOrThrow = createSelector(\n getPaymentMethod,\n (getPaymentMethod) => (methodId: string, gatewayId?: string) => {\n return guard(\n getPaymentMethod(methodId, gatewayId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentMethod),\n );\n },\n );\n\n const getLoadError = createSelector(\n (state: PaymentMethodState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getLoadMethodError = createSelector(\n (state: PaymentMethodState) => state.errors.loadMethodId,\n (state: PaymentMethodState) => state.errors.loadMethodError,\n (loadMethodId, loadMethodError) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return;\n }\n\n return loadMethodError;\n },\n );\n\n const isLoading = createSelector(\n (state: PaymentMethodState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isLoadingMethod = createSelector(\n (state: PaymentMethodState) => state.statuses.loadMethodId,\n (state: PaymentMethodState) => state.statuses.isLoadingMethod,\n (loadMethodId, isLoadingMethod) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return false;\n }\n\n return !!isLoadingMethod;\n },\n );\n\n return memoizeOne((state: PaymentMethodState = DEFAULT_STATE): PaymentMethodSelector => {\n return {\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethodsMeta: getPaymentMethodsMeta(state),\n getPaymentMethod: getPaymentMethod(state),\n getPaymentMethodOrThrow: getPaymentMethodOrThrow(state),\n getLoadError: getLoadError(state),\n getLoadMethodError: getLoadMethodError(state),\n isLoading: isLoading(state),\n isLoadingMethod: isLoadingMethod(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport PaymentStrategyState, { DEFAULT_STATE } from './payment-strategy-state';\n\ninterface InitiaizedQuery {\n methodId: string;\n gatewayId?: string;\n}\n\nexport default interface PaymentStrategySelector {\n getInitializeError(methodId?: string): Error | undefined;\n getExecuteError(methodId?: string): Error | undefined;\n getFinalizeError(methodId?: string): Error | undefined;\n getWidgetInteractingError(methodId?: string): Error | undefined;\n isInitializing(methodId?: string): boolean;\n isInitialized(query: InitiaizedQuery): boolean;\n isExecuting(methodId?: string): boolean;\n isFinalizing(methodId?: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type PaymentStrategySelectorFactory = (\n state: PaymentStrategyState,\n) => PaymentStrategySelector;\n\nexport function createPaymentStrategySelectorFactory(): PaymentStrategySelectorFactory {\n const getInitializeError = createSelector(\n (state: PaymentStrategyState) => state.errors.initializeMethodId,\n (state: PaymentStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getExecuteError = createSelector(\n (state: PaymentStrategyState) => state.errors.executeMethodId,\n (state: PaymentStrategyState) => state.errors.executeError,\n (executeMethodId, executeError) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return;\n }\n\n return executeError;\n },\n );\n\n const getFinalizeError = createSelector(\n (state: PaymentStrategyState) => state.errors.finalizeMethodId,\n (state: PaymentStrategyState) => state.errors.finalizeError,\n (finalizeMethodId, finalizeError) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return;\n }\n\n return finalizeError;\n },\n );\n\n const getWidgetInteractingError = createSelector(\n (state: PaymentStrategyState) => state.errors.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isInitializing = createSelector(\n (state: PaymentStrategyState) => state.statuses.initializeMethodId,\n (state: PaymentStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (key?: string) => {\n if (key && initializeMethodId !== key) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: PaymentStrategyState) => state.data,\n (data) => (query: InitiaizedQuery) => {\n const key = query.gatewayId ? `${query.methodId}.${query.gatewayId}` : query.methodId;\n\n return !!(data[key] && data[key].isInitialized);\n },\n );\n\n const isExecuting = createSelector(\n (state: PaymentStrategyState) => state.statuses.executeMethodId,\n (state: PaymentStrategyState) => state.statuses.isExecuting,\n (executeMethodId, isExecuting) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return false;\n }\n\n return !!isExecuting;\n },\n );\n\n const isFinalizing = createSelector(\n (state: PaymentStrategyState) => state.statuses.finalizeMethodId,\n (state: PaymentStrategyState) => state.statuses.isFinalizing,\n (finalizeMethodId, isFinalizing) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return false;\n }\n\n return !!isFinalizing;\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: PaymentStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: PaymentStrategyState = DEFAULT_STATE): PaymentStrategySelector => {\n return {\n getInitializeError: getInitializeError(state),\n getExecuteError: getExecuteError(state),\n getFinalizeError: getFinalizeError(state),\n getWidgetInteractingError: getWidgetInteractingError(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isExecuting: isExecuting(state),\n isFinalizing: isFinalizing(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { objectFlatten, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionResult, SearchArea } from './pickup-option';\nimport PickupOptionState, { DEFAULT_STATE } from './pickup-option-state';\n\nexport default interface PickupOptionSelector {\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type PickupOptionSelectorFactory = (state: PickupOptionState) => PickupOptionSelector;\n\nexport function createPickupOptionSelectorFactory(): PickupOptionSelectorFactory {\n const getPickupOptions = createSelector(\n (state: PickupOptionState) => state.data,\n (pickupOptions) => (consignmentId: string, searchArea: SearchArea) => {\n if (!pickupOptions) {\n return;\n }\n\n const flattenedParams = objectFlatten({ consignmentId, searchArea });\n const sortedFlattenedParams = objectWithSortedKeys(flattenedParams);\n const keyString = btoa(`${JSON.stringify(sortedFlattenedParams)}`);\n\n return pickupOptions[keyString];\n },\n );\n\n const getLoadError = createSelector(\n (state: PickupOptionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: PickupOptionState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: PickupOptionState = DEFAULT_STATE): PickupOptionSelector => {\n return {\n getPickupOptions: getPickupOptions(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport ShippingCountryState, { DEFAULT_STATE } from './shipping-country-state';\n\nexport default interface ShippingCountrySelector {\n getShippingCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ShippingCountrySelectorFactory = (\n state: ShippingCountryState,\n) => ShippingCountrySelector;\n\nexport function createShippingCountrySelectorFactory(): ShippingCountrySelectorFactory {\n const getShippingCountries = createSelector(\n (state: ShippingCountryState) => state.data,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ShippingCountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ShippingCountryState) => state.statuses.isLoading,\n (status) => () => !!status,\n );\n\n return memoizeOne((state: ShippingCountryState = DEFAULT_STATE): ShippingCountrySelector => {\n return {\n getShippingCountries: getShippingCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport ShippingStrategyState, { DEFAULT_STATE } from './shipping-strategy-state';\n\nexport default interface ShippingStrategySelector {\n getUpdateAddressError(methodId?: string): Error | undefined;\n getSelectOptionError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isUpdatingAddress(methodId?: string): boolean;\n isSelectingOption(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type ShippingStrategySelectorFactory = (\n state: ShippingStrategyState,\n) => ShippingStrategySelector;\n\nexport function createShippingStrategySelectorFactory(): ShippingStrategySelectorFactory {\n const getUpdateAddressError = createSelector(\n (state: ShippingStrategyState) => state.errors.updateAddressMethodId,\n (state: ShippingStrategyState) => state.errors.updateAddressError,\n (updateAddressMethodId, updateAddressError) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return;\n }\n\n return updateAddressError;\n },\n );\n\n const getSelectOptionError = createSelector(\n (state: ShippingStrategyState) => state.errors.selectOptionMethodId,\n (state: ShippingStrategyState) => state.errors.selectOptionError,\n (selectOptionMethodId, selectOptionError) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return;\n }\n\n return selectOptionError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: ShippingStrategyState) => state.errors.initializeMethodId,\n (state: ShippingStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: ShippingStrategyState) => state.errors.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isUpdatingAddress = createSelector(\n (state: ShippingStrategyState) => state.statuses.updateAddressMethodId,\n (state: ShippingStrategyState) => state.statuses.isUpdatingAddress,\n (updateAddressMethodId, isUpdatingAddress) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return false;\n }\n\n return !!isUpdatingAddress;\n },\n );\n\n const isSelectingOption = createSelector(\n (state: ShippingStrategyState) => state.statuses.selectOptionMethodId,\n (state: ShippingStrategyState) => state.statuses.isSelectingOption,\n (selectOptionMethodId, isSelectingOption) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return false;\n }\n\n return !!isSelectingOption;\n },\n );\n\n const isInitializing = createSelector(\n (state: ShippingStrategyState) => state.statuses.initializeMethodId,\n (state: ShippingStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: ShippingStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: ShippingStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: ShippingStrategyState = DEFAULT_STATE): ShippingStrategySelector => {\n return {\n getUpdateAddressError: getUpdateAddressError(state),\n getSelectOptionError: getSelectOptionError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isUpdatingAddress: isUpdatingAddress(state),\n isSelectingOption: isSelectingOption(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { AddressRequestBody, isAddressEqual } from '../address';\nimport { CartSelector, PhysicalItem } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Consignment from './consignment';\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\nimport ShippingOption from './shipping-option';\n\nexport default interface ConsignmentSelector {\n getConsignments(): Consignment[] | undefined;\n getConsignmentsOrThrow(): Consignment[];\n getConsignmentById(id: string): Consignment | undefined;\n getConsignmentByAddress(address: AddressRequestBody): Consignment | undefined;\n getShippingOption(): ShippingOption | undefined;\n getLoadError(): Error | undefined;\n getCreateError(): Error | undefined;\n getLoadShippingOptionsError(): Error | undefined;\n getUnassignedItems(): PhysicalItem[];\n getUpdateError(consignmentId?: string): Error | undefined;\n getDeleteError(consignmentId?: string): Error | undefined;\n getItemAssignmentError(address: AddressRequestBody): Error | undefined;\n getUpdateShippingOptionError(consignmentId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingShippingOptions(): boolean;\n isCreating(): boolean;\n isUpdating(consignmentId?: string): boolean;\n isDeleting(consignmentId?: string): boolean;\n isAssigningItems(address: AddressRequestBody): boolean;\n isUpdatingShippingOption(consignmentId?: string): boolean;\n}\n\nexport type ConsignmentSelectorFactory = (\n state: ConsignmentState,\n cart: CartSelector,\n) => ConsignmentSelector;\n\ninterface ConsignmentSelectorDependencies {\n cart: CartSelector;\n}\n\nexport function createConsignmentSelectorFactory(): ConsignmentSelectorFactory {\n const getConsignments = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => consignments,\n );\n\n const getConsignmentsOrThrow = createSelector(getConsignments, (getConsignments) => () => {\n return guard(\n getConsignments(),\n () => new MissingDataError(MissingDataErrorType.MissingConsignments),\n );\n });\n\n const getConsignmentById = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (id: string) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, { id });\n },\n );\n\n const getConsignmentByAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (address: AddressRequestBody) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, (consignment) =>\n isAddressEqual(consignment.shippingAddress, address),\n );\n },\n );\n\n const getShippingOption = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n if (consignments && consignments.length) {\n return consignments[0].selectedShippingOption;\n }\n },\n );\n\n const getLoadError = createSelector(\n (state: ConsignmentState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getCreateError = createSelector(\n (state: ConsignmentState) => state.errors.createError,\n (error) => () => error,\n );\n\n const getLoadShippingOptionsError = createSelector(\n (state: ConsignmentState) => state.errors.loadShippingOptionsError,\n (error) => () => error,\n );\n\n const getUnassignedItems = createSelector(\n getConsignments,\n (_: ConsignmentState, { cart }: ConsignmentSelectorDependencies) => cart.getCart,\n (getConsignments, getCart) => () => {\n const cart = getCart();\n\n if (!cart) {\n return [];\n }\n\n const assignedLineItemIds = (getConsignments() || []).reduce(\n (itemIds, consignment) => itemIds.concat(consignment.lineItemIds),\n [] as string[],\n );\n\n return (cart.lineItems.physicalItems || []).filter(\n (item) => assignedLineItemIds.indexOf(item.id as string) < 0,\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: ConsignmentState) => state.errors.updateError,\n (updateError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateError[consignmentId];\n }\n\n return find(updateError);\n },\n );\n\n const getDeleteError = createSelector(\n (state: ConsignmentState) => state.errors.deleteError,\n (deleteError) => (consignmentId?: string) => {\n if (consignmentId) {\n return deleteError[consignmentId];\n }\n\n return find(deleteError);\n },\n );\n\n const getItemAssignmentError = createSelector(\n getConsignmentByAddress,\n getUpdateError,\n getCreateError,\n (getConsignmentByAddress, getUpdateError, getCreateError) =>\n (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? getUpdateError(consignment.id) : getCreateError();\n },\n );\n\n const getUpdateShippingOptionError = createSelector(\n (state: ConsignmentState) => state.errors.updateShippingOptionError,\n (updateShippingOptionError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateShippingOptionError[consignmentId];\n }\n\n return find(updateShippingOptionError);\n },\n );\n\n const isLoading = createSelector(\n (state: ConsignmentState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isLoadingShippingOptions = createSelector(\n (state: ConsignmentState) => state.statuses.isLoadingShippingOptions,\n (isLoadingShippingOptions) => () => isLoadingShippingOptions === true,\n );\n\n const isCreating = createSelector(\n (state: ConsignmentState) => state.statuses.isCreating,\n (isCreating) => () => isCreating === true,\n );\n\n const isUpdating = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdating,\n (isUpdating) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdating[consignmentId] === true;\n }\n\n return find(isUpdating) === true;\n },\n );\n\n const isDeleting = createSelector(\n (state: ConsignmentState) => state.statuses.isDeleting,\n (isDeleting) => (consignmentId?: string) => {\n if (consignmentId) {\n return isDeleting[consignmentId] === true;\n }\n\n return find(isDeleting) === true;\n },\n );\n\n const isAssigningItems = createSelector(\n getConsignmentByAddress,\n isUpdating,\n isCreating,\n (getConsignmentByAddress, isUpdating, isCreating) => (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? isUpdating(consignment.id) : isCreating();\n },\n );\n\n const isUpdatingShippingOption = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdatingShippingOption,\n (isUpdatingShippingOption) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdatingShippingOption[consignmentId] === true;\n }\n\n return find(isUpdatingShippingOption) === true;\n },\n );\n\n return memoizeOne(\n (state: ConsignmentState = DEFAULT_STATE, cart: CartSelector): ConsignmentSelector => {\n return {\n getConsignments: getConsignments(state),\n getConsignmentsOrThrow: getConsignmentsOrThrow(state),\n getConsignmentById: getConsignmentById(state),\n getConsignmentByAddress: getConsignmentByAddress(state),\n getShippingOption: getShippingOption(state),\n getLoadError: getLoadError(state),\n getCreateError: getCreateError(state),\n getLoadShippingOptionsError: getLoadShippingOptionsError(state),\n getUnassignedItems: getUnassignedItems(state, { cart }),\n getUpdateError: getUpdateError(state),\n getDeleteError: getDeleteError(state),\n getItemAssignmentError: getItemAssignmentError(state),\n getUpdateShippingOptionError: getUpdateShippingOptionError(state),\n isLoading: isLoading(state),\n isLoadingShippingOptions: isLoadingShippingOptions(state),\n isCreating: isCreating(state),\n isUpdating: isUpdating(state),\n isDeleting: isDeleting(state),\n isAssigningItems: isAssigningItems(state),\n isUpdatingShippingOption: isUpdatingShippingOption(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { CartSelector } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector, GiftCertificateSelector } from '../coupon';\nimport { CustomerSelector } from '../customer';\nimport { ConsignmentSelector } from '../shipping';\n\nimport Checkout from './checkout';\nimport CheckoutState, { DEFAULT_STATE } from './checkout-state';\n\nexport default interface CheckoutSelector {\n getCheckout(): Checkout | undefined;\n getCheckoutOrThrow(): Checkout;\n getOutstandingBalance(useStoreCredit?: boolean): number | undefined;\n getLoadError(): Error | undefined;\n getUpdateError(): Error | undefined;\n isExecutingSpamCheck(): boolean;\n isLoading(): boolean;\n isUpdating(): boolean;\n}\n\nexport type CheckoutSelectorFactory = (\n state: CheckoutState,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n) => CheckoutSelector;\n\ninterface CheckoutSelectorDependencies {\n billingAddress: BillingAddressSelector;\n cart: CartSelector;\n consignments: ConsignmentSelector;\n coupons: CouponSelector;\n customer: CustomerSelector;\n giftCertificates: GiftCertificateSelector;\n}\n\nexport function createCheckoutSelectorFactory(): CheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: CheckoutState) => state.data,\n (_: CheckoutState, { billingAddress }: CheckoutSelectorDependencies) =>\n billingAddress.getBillingAddress,\n (_: CheckoutState, { cart }: CheckoutSelectorDependencies) => cart.getCart,\n (_: CheckoutState, { customer }: CheckoutSelectorDependencies) => customer.getCustomer,\n (_: CheckoutState, { consignments }: CheckoutSelectorDependencies) =>\n consignments.getConsignments,\n (_: CheckoutState, { coupons }: CheckoutSelectorDependencies) => coupons.getCoupons,\n (_: CheckoutState, { giftCertificates }: CheckoutSelectorDependencies) =>\n giftCertificates.getGiftCertificates,\n (\n data,\n getBillingAddress,\n getCart,\n getCustomer,\n getConsignments,\n getCoupons,\n getGiftCertificates,\n ) =>\n () => {\n const billingAddress = getBillingAddress();\n const cart = getCart();\n const customer = getCustomer();\n const consignments = getConsignments() || [];\n const coupons = getCoupons() || [];\n const giftCertificates = getGiftCertificates() || [];\n\n if (!data || !cart || !customer) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n cart,\n customer,\n consignments,\n coupons,\n giftCertificates,\n };\n },\n );\n\n const getCheckoutOrThrow = createSelector(getCheckout, (getCheckout) => () => {\n return guard(\n getCheckout(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckout),\n );\n });\n\n const getOutstandingBalance = createSelector(\n getCheckout,\n (getCheckout) => (useStoreCredit?: boolean) => {\n const checkout = getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const grandTotal = checkout.grandTotal || 0;\n const storeCredit = checkout.customer.storeCredit || 0;\n\n return useStoreCredit\n ? Math.max(grandTotal - storeCredit, 0)\n : checkout.outstandingBalance;\n },\n );\n\n const getLoadError = createSelector(\n (state: CheckoutState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getUpdateError = createSelector(\n (state: CheckoutState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isExecutingSpamCheck = createSelector(\n (state: CheckoutState) => state.statuses.isExecutingSpamCheck,\n (isExecutingSpamCheck) => () => isExecutingSpamCheck === true,\n );\n\n const isLoading = createSelector(\n (state: CheckoutState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isUpdating = createSelector(\n (state: CheckoutState) => state.statuses.isUpdating,\n (isUpdating) => () => isUpdating === true,\n );\n\n return memoizeOne(\n (\n state: CheckoutState = DEFAULT_STATE,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n ): CheckoutSelector => {\n return {\n getCheckout: getCheckout(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getCheckoutOrThrow: getCheckoutOrThrow(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getOutstandingBalance: getOutstandingBalance(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getLoadError: getLoadError(state),\n getUpdateError: getUpdateError(state),\n isExecutingSpamCheck: isExecutingSpamCheck(state),\n isLoading: isLoading(state),\n isUpdating: isUpdating(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector } from '../coupon';\nimport OrderBillingAddressSelector from '../order-billing-address/order-billing-address-selector';\n\nimport Order from './order';\nimport OrderState, { DEFAULT_STATE, OrderMetaState } from './order-state';\n\nexport default interface OrderSelector {\n getOrder(): Order | undefined;\n getOrderOrThrow(): Order;\n getOrderMeta(): OrderMetaState | undefined;\n getLoadError(): Error | undefined;\n getPaymentId(methodId: string): string | undefined;\n isLoading(): boolean;\n}\n\nexport type OrderSelectorFactory = (\n state: OrderState,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n) => OrderSelector;\n\ninterface OrderSelectorDependencies {\n billingAddress: OrderBillingAddressSelector;\n coupons: CouponSelector;\n}\n\nexport function createOrderSelectorFactory(): OrderSelectorFactory {\n const getOrder = createSelector(\n (state: OrderState) => state.data,\n (_: OrderState, { billingAddress }: OrderSelectorDependencies) =>\n billingAddress.getOrderBillingAddress(),\n (_: OrderState, { coupons }: OrderSelectorDependencies) => coupons.getCoupons(),\n (data, billingAddress, coupons = []) =>\n () => {\n if (!data || !billingAddress) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n coupons,\n };\n },\n );\n\n const getOrderOrThrow = createSelector(getOrder, (getOrder) => () => {\n return guard(getOrder(), () => new MissingDataError(MissingDataErrorType.MissingOrder));\n });\n\n const getOrderMeta = createSelector(\n (state: OrderState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: OrderState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getPaymentId = createSelector(\n (state: OrderState) => state.data?.payments,\n (payments = []) =>\n (methodId: string) => {\n const currentPayment = payments.find(({ providerId }) => providerId === methodId);\n\n return currentPayment?.paymentId;\n },\n );\n\n const isLoading = createSelector(\n (state: OrderState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (\n state: OrderState = DEFAULT_STATE,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n ): OrderSelector => {\n return {\n getOrder: getOrder(state, { billingAddress, coupons }),\n getOrderOrThrow: getOrderOrThrow(state, { billingAddress, coupons }),\n getOrderMeta: getOrderMeta(state),\n getLoadError: getLoadError(state),\n getPaymentId: getPaymentId(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport StoreCreditState, { DEFAULT_STATE } from './store-credit-state';\n\nexport default interface StoreCreditSelector {\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n}\n\nexport type StoreCreditSelectorFactory = (state: StoreCreditState) => StoreCreditSelector;\n\nexport function createStoreCreditSelectorFactory(): StoreCreditSelectorFactory {\n const getApplyError = createSelector(\n (state: StoreCreditState) => state.errors.applyError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: StoreCreditState) => !!state.statuses.isApplying,\n (status) => () => status,\n );\n\n return memoizeOne((state: StoreCreditState = DEFAULT_STATE): StoreCreditSelector => {\n return {\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport SubscriptionsState, { DEFAULT_STATE } from './subscriptions-state';\n\nexport default interface SubscriptionsSelector {\n getUpdateError(): Error | undefined;\n isUpdating(): boolean;\n}\n\nexport type SubscriptionsSelectorFactory = (state: SubscriptionsState) => SubscriptionsSelector;\n\nexport function createSubscriptionsSelectorFactory(): SubscriptionsSelectorFactory {\n const getUpdateError = createSelector(\n (state: SubscriptionsState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: SubscriptionsState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n return memoizeOne((state: SubscriptionsState = DEFAULT_STATE): SubscriptionsSelector => {\n return {\n getUpdateError: getUpdateError(state),\n isUpdating: isUpdating(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { Extension, ExtensionRegion } from './extension';\nimport { DEFAULT_STATE, ExtensionState } from './extension-state';\n\nexport interface ExtensionSelector {\n getExtensions(): Extension[] | undefined;\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ExtensionSelectorFactory = (state: ExtensionState) => ExtensionSelector;\n\nexport function createExtensionSelectorFactory(): ExtensionSelectorFactory {\n const getExtensions = createSelector(\n (state: ExtensionState) => state.data,\n (data) => () => data,\n );\n\n const getExtensionByRegion = createSelector(\n (state: ExtensionState) => state.data,\n (data) => (region: ExtensionRegion) => data?.find((e) => e.region === region),\n );\n\n const getLoadError = createSelector(\n (state: ExtensionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ExtensionState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n return memoizeOne((state: ExtensionState = DEFAULT_STATE): ExtensionSelector => {\n return {\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { createDataStore } from '@bigcommerce/data-store';\n\nimport { createRequestErrorFactory } from '../common/error';\n\nimport CheckoutStore, { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport createActionTransformer from './create-action-transformer';\nimport createCheckoutStoreReducer from './create-checkout-store-reducer';\nimport { createInternalCheckoutSelectorsFactory } from './create-internal-checkout-selectors';\n\nexport default function createCheckoutStore(\n initialState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n\n return createDataStore(createCheckoutStoreReducer(), initialState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnrecoverableError } from './errors';\nimport RequestErrorFactory from './request-error-factory';\n\nexport default function createRequestErrorFactory(): RequestErrorFactory {\n const factory = new RequestErrorFactory();\n\n const unrecoverableErrorTypes = [\n 'catalog_only',\n 'empty_cart',\n 'invalid_order_id',\n 'invalid_order_token',\n 'missing_order_token',\n 'missing_provider_token',\n 'missing_shipping_method',\n 'order_completion_error',\n 'order_could_not_be_finalized_error',\n 'order_create_failed',\n 'provider_fatal_error',\n 'provider_setup_error',\n 'stock_too_low',\n ];\n\n unrecoverableErrorTypes.forEach((type) => {\n factory.register(type, (response, message) => new UnrecoverableError(response, message));\n });\n\n factory.register(\n 'invalid_payment_provider',\n (response) => new PaymentMethodInvalidError(response),\n );\n factory.register(\n 'payment_config_not_found',\n (response) => new PaymentMethodInvalidError(response),\n );\n\n return factory;\n}\n","import { Action } from '@bigcommerce/data-store';\nimport { from, Observable, Subscribable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { RequestErrorFactory } from '../common/error';\n\nexport default function createActionTransformer(\n requestErrorFactory: RequestErrorFactory,\n): (action: Subscribable) => Observable {\n return (action$) =>\n from(action$).pipe(\n catchError((action) => {\n if (action instanceof Error || action.payload instanceof Error) {\n throw action;\n }\n\n if (isResponse(action.payload)) {\n const message = action.payload.body && action.payload.body.detail;\n\n throw {\n ...action,\n payload: requestErrorFactory.createError(action.payload, message),\n };\n }\n\n throw action;\n }),\n );\n}\n\nfunction isResponse(object: any) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n\n return ['body', 'headers', 'status', 'statusText'].every((key) =>\n Object.prototype.hasOwnProperty.call(object, key),\n );\n}\n","import { Action, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { billingAddressReducer } from '../billing';\nimport { cartReducer } from '../cart';\nimport { checkoutButtonReducer } from '../checkout-buttons';\nimport { configReducer } from '../config';\nimport { couponReducer, giftCertificateReducer } from '../coupon';\nimport { customerReducer, customerStrategyReducer } from '../customer';\nimport { extensionReducer } from '../extension';\nimport { formFieldsReducer } from '../form';\nimport { countryReducer } from '../geography';\nimport { orderReducer } from '../order';\nimport { orderBillingAddressReducer } from '../order-billing-address';\nimport { paymentMethodReducer, paymentReducer, paymentStrategyReducer } from '../payment';\nimport { paymentProviderCustomerReducer } from '../payment-provider-customer';\nimport { instrumentReducer } from '../payment/instrument';\nimport { remoteCheckoutReducer } from '../remote-checkout';\nimport {\n consignmentReducer,\n pickupOptionReducer,\n shippingCountryReducer,\n shippingStrategyReducer,\n} from '../shipping';\nimport { signInEmailReducer } from '../signin-email';\nimport { storeCreditReducer } from '../store-credit';\nimport { subscriptionsReducer } from '../subscription';\n\nimport checkoutReducer from './checkout-reducer';\nimport CheckoutStoreState from './checkout-store-state';\n\nexport default function createCheckoutStoreReducer(): Reducer {\n return combineReducers({\n billingAddress: billingAddressReducer,\n cart: cartReducer,\n checkout: checkoutReducer,\n checkoutButton: checkoutButtonReducer,\n config: configReducer,\n consignments: consignmentReducer,\n countries: countryReducer,\n coupons: couponReducer,\n customer: customerReducer,\n customerStrategies: customerStrategyReducer,\n extensions: extensionReducer,\n formFields: formFieldsReducer,\n giftCertificates: giftCertificateReducer,\n instruments: instrumentReducer,\n orderBillingAddress: orderBillingAddressReducer,\n order: orderReducer,\n payment: paymentReducer,\n paymentMethods: paymentMethodReducer,\n paymentStrategies: paymentStrategyReducer,\n pickupOptions: pickupOptionReducer,\n paymentProviderCustomer: paymentProviderCustomerReducer,\n remoteCheckout: remoteCheckoutReducer,\n shippingCountries: shippingCountryReducer,\n shippingStrategies: shippingStrategyReducer,\n signInEmail: signInEmailReducer,\n subscriptions: subscriptionsReducer,\n storeCredit: storeCreditReducer,\n });\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { createDataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator } from '../common/error';\nimport { getDefaultLogger } from '../common/log';\nimport { getEnvironment } from '../common/utility';\nimport { ConfigActionCreator, ConfigRequestSender, ConfigState, ConfigWindow } from '../config';\nimport {\n CouponActionCreator,\n CouponRequestSender,\n GiftCertificateActionCreator,\n GiftCertificateRequestSender,\n} from '../coupon';\nimport {\n createCustomerStrategyRegistry,\n createCustomerStrategyRegistryV2,\n CustomerActionCreator,\n CustomerRequestSender,\n CustomerStrategyActionCreator,\n} from '../customer';\nimport {\n createExtensionEventBroadcaster,\n ExtensionActionCreator,\n ExtensionMessenger,\n ExtensionRequestSender,\n} from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\nimport { CountryActionCreator, CountryRequestSender } from '../geography';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n createPaymentStrategyRegistry,\n createPaymentStrategyRegistryV2,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { InstrumentActionCreator, InstrumentRequestSender } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n createShippingStrategyRegistry,\n PickupOptionActionCreator,\n PickupOptionRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestSender } from '../signin-email';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport CheckoutService from './checkout-service';\nimport CheckoutValidator from './checkout-validator';\nimport { createCheckoutSelectorsFactory } from './create-checkout-selectors';\nimport createCheckoutStore from './create-checkout-store';\n\n/**\n * Creates an instance of `CheckoutService`.\n *\n * @remarks\n * ```js\n * const service = createCheckoutService();\n *\n * service.subscribe(state => {\n * console.log(state);\n * });\n *\n * service.loadCheckout();\n * ```\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutService`.\n */\nexport default function createCheckoutService(options?: CheckoutServiceOptions): CheckoutService {\n if (document.location.protocol !== 'https:') {\n getDefaultLogger().warn(\n 'The BigCommerce Checkout SDK should not be used on a non-HTTPS page',\n );\n }\n\n if (getEnvironment() !== 'production') {\n getDefaultLogger().warn(\n 'Note that the development build is not optimized. To create a production build, set process\\u200b.env.NODE_ENV to `production`.',\n );\n }\n\n const config: ConfigState = {\n meta: {\n externalSource: options && options.externalSource,\n host: options?.host,\n locale: options?.locale,\n variantIdentificationToken: (window as ConfigWindow).checkoutVariantIdentificationToken,\n },\n errors: {},\n statuses: {},\n };\n const { locale = '', shouldWarnMutation = true } = options || {};\n const requestSender = createRequestSender({ host: options && options.host });\n const store = createCheckoutStore({ config }, { shouldWarnMutation });\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(requestSender);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n const orderActionCreator = new OrderActionCreator(\n orderRequestSender,\n new CheckoutValidator(checkoutRequestSender),\n );\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n defaultPaymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(requestSender),\n );\n const extensionMessenger = new ExtensionMessenger(store);\n const storeProjection = createDataStoreProjection(store, createCheckoutSelectorsFactory());\n\n return new CheckoutService(\n store,\n storeProjection,\n extensionMessenger,\n createExtensionEventBroadcaster(storeProjection, extensionMessenger),\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(requestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(requestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, requestSender, locale),\n customerRegistryV2,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(requestSender)),\n new InstrumentActionCreator(new InstrumentRequestSender(paymentClient, requestSender)),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(\n store,\n paymentClient,\n requestSender,\n spamProtection,\n locale,\n ),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(requestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale }),\n store,\n ),\n new ShippingStrategyActionCreator(createShippingStrategyRegistry(store, requestSender)),\n new SignInEmailActionCreator(new SignInEmailRequestSender(requestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { omit, values } from 'lodash';\n\nimport { Address } from '../address';\nimport { BillingAddress } from '../billing';\nimport { Cart } from '../cart';\nimport { createSelector } from '../common/selector';\nimport { cloneResult as clone } from '../common/utility';\nimport { FlashMessage, FlashMessageType, StoreConfig, UserExperienceSettings } from '../config';\nimport { Coupon, GiftCertificate } from '../coupon';\nimport { Customer } from '../customer';\nimport { Extension, ExtensionRegion } from '../extension';\nimport { FormField } from '../form';\nimport { Country } from '../geography';\nimport { Order } from '../order';\nimport { PaymentMethod } from '../payment';\nimport { PaymentProviderCustomer } from '../payment-provider-customer';\nimport { CardInstrument, PaymentInstrument } from '../payment/instrument';\nimport { Consignment, PickupOptionResult, SearchArea, ShippingOption } from '../shipping';\nimport { SignInEmail } from '../signin-email';\n\nimport Checkout from './checkout';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type Instrument = CardInstrument;\n\n/**\n * Responsible for getting the state of the current checkout.\n *\n * This object has a set of methods that allow you to get a specific piece of\n * checkout information, such as shipping and billing details.\n */\nexport default interface CheckoutStoreSelector {\n /**\n * Gets the current checkout.\n *\n * @returns The current checkout if it is loaded, otherwise undefined.\n */\n getCheckout(): Checkout | undefined;\n\n /**\n * Gets the current order.\n *\n * @returns The current order if it is loaded, otherwise undefined.\n */\n getOrder(): Order | undefined;\n\n /**\n * Gets the checkout configuration of a store.\n *\n * @returns The configuration object if it is loaded, otherwise undefined.\n */\n getConfig(): StoreConfig | undefined;\n\n /**\n * Gets the sign-in email.\n *\n * @returns The sign-in email object if sent, otherwise undefined\n */\n getSignInEmail(): SignInEmail | undefined;\n\n /**\n * Gets the shipping address of the current checkout.\n *\n * If the address is partially complete, it may not have shipping options\n * associated with it.\n *\n * @returns The shipping address object if it is loaded, otherwise\n * undefined.\n */\n getShippingAddress(): Address | undefined;\n\n /**\n * Gets a list of shipping options available for the shipping address.\n *\n * If there is no shipping address assigned to the current checkout, the\n * list of shipping options will be empty.\n *\n * @returns The list of shipping options if any, otherwise undefined.\n */\n getShippingOptions(): ShippingOption[] | undefined;\n\n /**\n * Gets a list of consignments.\n *\n * If there are no consignments created for to the current checkout, the\n * list will be empty.\n *\n * @returns The list of consignments if any, otherwise undefined.\n */\n getConsignments(): Consignment[] | undefined;\n\n /**\n * Gets the selected shipping option for the current checkout.\n *\n * @returns The shipping option object if there is a selected option,\n * otherwise undefined.\n */\n getSelectedShippingOption(): ShippingOption | undefined;\n\n /**\n * Gets a list of countries available for shipping.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getShippingCountries(): Country[] | undefined;\n\n /**\n * Gets the billing address of an order.\n *\n * @returns The billing address object if it is loaded, otherwise undefined.\n */\n getBillingAddress(): BillingAddress | undefined;\n\n /**\n * Gets a list of countries available for billing.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getBillingCountries(): Country[] | undefined;\n\n /**\n * Gets a list of payment methods available for checkout.\n *\n * @returns The list of payment methods if it is loaded, otherwise undefined.\n */\n getPaymentMethods(): PaymentMethod[] | undefined;\n\n /**\n * Gets a payment method by an id.\n *\n * The method returns undefined if unable to find a payment method with the\n * specified id, either because it is not available for the customer, or it\n * is not loaded.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns The payment method object if loaded and available, otherwise,\n * undefined.\n */\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n\n /**\n * Gets the payment method that is selected for checkout.\n *\n * @returns The payment method object if there is a selected method;\n * undefined if otherwise.\n */\n getSelectedPaymentMethod(): PaymentMethod | undefined;\n\n /**\n * Gets the available flash messages.\n *\n * Flash messages contain messages set by the server,\n * e.g: when trying to sign in using an invalid email link.\n *\n * @param type - The type of flash messages to be returned. Optional\n * @returns The flash messages if available, otherwise undefined.\n */\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n\n /**\n * Gets the current cart.\n *\n * @returns The current cart object if it is loaded, otherwise undefined.\n */\n getCart(): Cart | undefined;\n\n /**\n * Gets a list of coupons that are applied to the current checkout.\n *\n * @returns The list of applied coupons if there is any, otherwise undefined.\n */\n getCoupons(): Coupon[] | undefined;\n\n /**\n * Gets a list of gift certificates that are applied to the current checkout.\n *\n * @returns The list of applied gift certificates if there is any, otherwise undefined.\n */\n getGiftCertificates(): GiftCertificate[] | undefined;\n\n /**\n * Gets the current customer.\n *\n * @returns The current customer object if it is loaded, otherwise\n * undefined.\n */\n getCustomer(): Customer | undefined;\n\n /**\n * Checks if payment data is required or not.\n *\n * If payment data is required, customers should be prompted to enter their\n * payment details.\n *\n * ```js\n * if (state.checkout.isPaymentDataRequired()) {\n * // Render payment form\n * } else {\n * // Render \"Payment is not required for this order\" message\n * }\n * ```\n *\n * @param useStoreCredit - If true, check whether payment data is required\n * with store credit applied; otherwise, check without store credit.\n * @returns True if payment data is required, otherwise false.\n */\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n\n /**\n * Checks if payment data is submitted or not.\n *\n * If payment data is already submitted using a payment method, customers\n * should not be prompted to enter their payment details again.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns True if payment data is submitted, otherwise false.\n */\n isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean;\n\n /**\n * Gets a list of payment instruments associated with the current customer.\n *\n * @returns The list of payment instruments if it is loaded, otherwise undefined.\n */\n getInstruments(): Instrument[] | undefined;\n getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n\n /**\n * Gets a set of form fields that should be presented in order to create a customer.\n *\n * @returns The set of customer account form fields if it is loaded,\n * otherwise undefined.\n */\n getCustomerAccountFields(): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their billing address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of billing address form fields if it is loaded,\n * otherwise undefined.\n */\n getBillingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their shipping address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getShippingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a list of pickup options for specified parameters.\n *\n * @param consignmentId - Id of consignment.\n * @param searchArea - An object containing of radius and co-ordinates.\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n\n /**\n * Gets user experience settings.\n *\n * @returns The object of user experience settings if it is loaded, otherwise undefined.\n */\n getUserExperienceSettings(): UserExperienceSettings | undefined;\n\n /**\n * Gets a list of extensions available for checkout.\n *\n * @alpha\n * @returns The list of extensions if it is loaded, otherwise undefined.\n */\n getExtensions(): Extension[] | undefined;\n\n /**\n * Gets payment provider customers data.\n *\n * @alpha\n * @returns The object with payment provider customer data\n */\n getPaymentProviderCustomer(): PaymentProviderCustomer | undefined;\n\n /**\n * Gets the extension associated with a given region.\n *\n * @alpha\n * @param region - A checkout extension region.\n * @returns The extension corresponding to the specified region, otherwise undefined.\n */\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n}\n\nexport type CheckoutStoreSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreSelector;\n\nexport function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory {\n const getCheckout = createSelector(\n ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout,\n (getCheckout) => clone(getCheckout),\n );\n\n const getOrder = createSelector(\n ({ order }: InternalCheckoutSelectors) => order.getOrder,\n (getOrder) => clone(getOrder),\n );\n\n const getConfig = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) => clone(getStoreConfig),\n );\n\n const getShippingAddress = createSelector(\n ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getShippingAddress, getContextConfig) =>\n clone(() => {\n const shippingAddress = getShippingAddress();\n const context = getContextConfig();\n\n if (!shippingAddress) {\n if (!context || !context.geoCountryCode) {\n return;\n }\n\n return {\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return shippingAddress;\n }),\n );\n\n const getShippingOptions = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.availableShippingOptions;\n }),\n );\n\n const getConsignments = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) => clone(getConsignments),\n );\n\n const getSelectedShippingOption = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.selectedShippingOption;\n }),\n );\n\n const getShippingCountries = createSelector(\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingCountries) => clone(getShippingCountries),\n );\n\n const getBillingAddress = createSelector(\n ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getBillingAddress, getContextConfig) =>\n clone(() => {\n const billingAddress = getBillingAddress();\n const context = getContextConfig();\n const isEmptyBillingAddress =\n !billingAddress ||\n values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id')).every(\n (val) => !val || !val.length,\n );\n\n if (isEmptyBillingAddress) {\n if (!context || !context.geoCountryCode) {\n return billingAddress;\n }\n\n return {\n id: billingAddress ? billingAddress.id : '',\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n email: billingAddress ? billingAddress.email : '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return billingAddress;\n }),\n );\n\n const getBillingCountries = createSelector(\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getCountries) => clone(getCountries),\n );\n\n const getPaymentMethods = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods,\n (getPaymentMethods) => clone(getPaymentMethods),\n );\n\n const getPaymentMethod = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentMethod) => clone(getPaymentMethod),\n );\n\n const getSelectedPaymentMethod = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentId, getPaymentMethod) =>\n clone(() => {\n const payment = getPaymentId();\n\n return payment && getPaymentMethod(payment.providerId, payment.gatewayId);\n }),\n );\n\n const getCart = createSelector(\n ({ cart }: InternalCheckoutSelectors) => cart.getCart,\n (getCart) => clone(getCart),\n );\n\n const getCoupons = createSelector(\n ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons,\n (getCoupons) => clone(getCoupons),\n );\n\n const getGiftCertificates = createSelector(\n ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates,\n (getGiftCertificates) => clone(getGiftCertificates),\n );\n\n const getCustomer = createSelector(\n ({ customer }: InternalCheckoutSelectors) => customer.getCustomer,\n (getCustomer) => clone(getCustomer),\n );\n\n const getSignInEmail = createSelector(\n ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail,\n (getEmail) => clone(getEmail),\n );\n\n const isPaymentDataRequired = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired,\n (isPaymentDataRequired) => clone(isPaymentDataRequired),\n );\n\n const isPaymentDataSubmitted = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (isPaymentDataSubmitted, getPaymentMethod) =>\n clone((methodId: string, gatewayId?: string) => {\n return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId));\n }),\n );\n\n const getInstruments = createSelector(\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments,\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod,\n (getInstruments, getInstrumentsByPaymentMethod) => {\n function getInstrumentsSelector(): Instrument[] | undefined;\n function getInstrumentsSelector(\n paymentMethod: PaymentMethod,\n ): PaymentInstrument[] | undefined;\n\n function getInstrumentsSelector(\n paymentMethod?: PaymentMethod,\n ): PaymentInstrument[] | undefined {\n return paymentMethod\n ? getInstrumentsByPaymentMethod(paymentMethod)\n : getInstruments();\n }\n\n return clone(getInstrumentsSelector);\n },\n );\n\n const getCustomerAccountFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields,\n (getCustomerAccountFields) => clone(getCustomerAccountFields),\n );\n\n const getBillingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields,\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getBillingAddressFields, getCountries) =>\n clone((countryCode: string) => {\n return getBillingAddressFields(getCountries(), countryCode);\n }),\n );\n\n const getShippingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields,\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingAddressFields, getShippingCountries) =>\n clone((countryCode: string) => {\n return getShippingAddressFields(getShippingCountries(), countryCode);\n }),\n );\n\n const getFlashMessages = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getFlashMessages,\n (getFlashMessages) => clone(getFlashMessages),\n );\n\n const getPickupOptions = createSelector(\n ({ pickupOptions }: InternalCheckoutSelectors) => pickupOptions.getPickupOptions,\n (getPickupOptions) => clone(getPickupOptions),\n );\n\n const getUserExperienceSettings = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) =>\n clone(() => {\n const config = getStoreConfig();\n\n if (!config) {\n return;\n }\n\n return config.checkoutSettings.checkoutUserExperienceSettings;\n }),\n );\n\n const getExtensions = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensions,\n (getExtensions) => clone(getExtensions),\n );\n\n const getPaymentProviderCustomer = createSelector(\n ({ paymentProviderCustomer }: InternalCheckoutSelectors) =>\n paymentProviderCustomer.getPaymentProviderCustomer,\n (getPaymentProviderCustomer) => clone(getPaymentProviderCustomer),\n );\n\n const getExtensionByRegion = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensionByRegion,\n (getExtensionByRegion) => clone(getExtensionByRegion),\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreSelector => {\n return {\n getCheckout: getCheckout(state),\n getOrder: getOrder(state),\n getConfig: getConfig(state),\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getFlashMessages: getFlashMessages(state),\n getShippingAddress: getShippingAddress(state),\n getShippingOptions: getShippingOptions(state),\n getConsignments: getConsignments(state),\n getSelectedShippingOption: getSelectedShippingOption(state),\n getShippingCountries: getShippingCountries(state),\n getBillingAddress: getBillingAddress(state),\n getBillingCountries: getBillingCountries(state),\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethod: getPaymentMethod(state),\n getSelectedPaymentMethod: getSelectedPaymentMethod(state),\n getCart: getCart(state),\n getCoupons: getCoupons(state),\n getGiftCertificates: getGiftCertificates(state),\n getCustomer: getCustomer(state),\n isPaymentDataRequired: isPaymentDataRequired(state),\n isPaymentDataSubmitted: isPaymentDataSubmitted(state),\n getSignInEmail: getSignInEmail(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n getPaymentProviderCustomer: getPaymentProviderCustomer(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { CartChangedError, CartConsistencyError } from '../cart/errors';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for getting the error of any asynchronous checkout action, if\n * there is any.\n *\n * This object has a set of getters that would return an error if an action is\n * not executed successfully. For example, if you are unable to submit an order,\n * you can use this object to retrieve the reason for the failure.\n */\nexport default interface CheckoutStoreErrorSelector {\n getError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current checkout.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to update the current checkout.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to submit the current order.\n *\n * @returns The error object if unable to submit, otherwise undefined.\n */\n getSubmitOrderError(): Error | CartChangedError | CartConsistencyError | undefined;\n\n /**\n * Returns an error if unable to finalize the current order.\n *\n * @returns The error object if unable to finalize, otherwise undefined.\n */\n getFinalizeOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current order.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current cart.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCartError(): Error | undefined;\n\n /**\n * Returns an error if unable to load billing countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadBillingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load payment methods.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodsError(): Error | undefined;\n\n /**\n * Returns an error if unable to load a specific payment method.\n *\n * @param methodId - The identifier of the payment method to load.\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to initialize a specific payment method.\n *\n * @param methodId - The identifier of the payment method to initialize.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializePaymentError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to sign in.\n *\n * @returns The error object if unable to sign in, otherwise undefined.\n */\n getSignInError(): Error | undefined;\n\n /**\n * Returns an error if unable to sign out.\n *\n * @returns The error object if unable to sign out, otherwise undefined.\n */\n getSignOutError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the customer step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeCustomerError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping options.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to select a shipping option.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to select, otherwise undefined.\n */\n getSelectShippingOptionError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to continue as guest.\n *\n * The call could fail in scenarios where guest checkout is not allowed, for example, when existing accounts are required to sign-in.\n *\n * In the background, this call tries to set the billing address email using the Storefront API. You could access the Storefront API response status code using `getContinueAsGuestError` error selector.\n *\n * ```js\n * console.log(state.errors.getContinueAsGuestError());\n * console.log(state.errors.getContinueAsGuestError().status);\n * ```\n *\n * For more information about status codes, check [Checkout Storefront API - Add Checkout Billing Address](https://developer.bigcommerce.com/api-reference/cart-checkout/storefront-checkout-api/checkout-billing-address/checkoutsbillingaddressbycheckoutidpost).\n *\n * @returns The error object if unable to continue, otherwise undefined.\n */\n getContinueAsGuestError(): Error | undefined;\n\n /**\n * Returns an error if unable to update billing address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateBillingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to update subscriptions.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateSubscriptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to update shipping address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateShippingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to update a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to create consignments.\n *\n * @returns The error object if unable to create, otherwise undefined.\n */\n getCreateConsignmentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the shipping step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeShippingError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to apply store credit.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyStoreCreditError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a coupon code.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a coupon code.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a gift certificate.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a gift certificate.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to load payment instruments.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadInstrumentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a payment instrument.\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteInstrumentError(instrumentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load the checkout configuration of a store.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadConfigError(): Error | undefined;\n\n /**\n * Returns an error if unable to send sign-in email.\n *\n * @returns The error object if unable to send email, otherwise undefined.\n */\n getSignInEmailError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer account.\n *\n * @returns The error object if unable to create account, otherwise undefined.\n */\n getCreateCustomerAccountError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer address.\n *\n * @returns The error object if unable to create address, otherwise undefined.\n */\n getCreateCustomerAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch pickup options.\n *\n * @returns The error object if unable to fetch pickup options, otherwise undefined.\n */\n getPickupOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch extensions.\n *\n * @alpha\n * @returns The error object if unable to fetch extensions, otherwise undefined.\n */\n getLoadExtensionsError(): Error | undefined;\n}\n\nexport type CheckoutStoreErrorSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreErrorSelector;\n\nexport function createCheckoutStoreErrorSelectorFactory(): CheckoutStoreErrorSelectorFactory {\n const getError = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n for (const key of Object.keys(selector) as Array<\n keyof Omit\n >) {\n const error = selector[key]();\n\n if (error) {\n return error;\n }\n }\n },\n );\n\n const getSelectShippingOptionError = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.getSelectOptionError,\n ({ consignments }: InternalCheckoutSelectors) => consignments.getUpdateShippingOptionError,\n (getSelectOptionError, getUpdateShippingOptionError) => (consignmentId?: string) => {\n return getSelectOptionError() || getUpdateShippingOptionError(consignmentId);\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreErrorSelector => {\n const selector = {\n getLoadCheckoutError: state.checkout.getLoadError,\n getUpdateCheckoutError: state.checkout.getUpdateError,\n getSubmitOrderError: state.paymentStrategies.getExecuteError,\n getFinalizeOrderError: state.paymentStrategies.getFinalizeError,\n getLoadOrderError: state.order.getLoadError,\n getLoadCartError: state.cart.getLoadError,\n getLoadBillingCountriesError: state.countries.getLoadError,\n getLoadShippingCountriesError: state.shippingCountries.getLoadError,\n getLoadPaymentMethodsError: state.paymentMethods.getLoadError,\n getLoadPaymentMethodError: state.paymentMethods.getLoadMethodError,\n getInitializePaymentError: state.paymentStrategies.getInitializeError,\n getSignInError: state.customerStrategies.getSignInError,\n getSignOutError: state.customerStrategies.getSignOutError,\n getInitializeCustomerError: state.customerStrategies.getInitializeError,\n getLoadShippingOptionsError: state.consignments.getLoadShippingOptionsError,\n getSelectShippingOptionError: getSelectShippingOptionError(state),\n getContinueAsGuestError: state.billingAddress.getContinueAsGuestError,\n getUpdateBillingAddressError: state.billingAddress.getUpdateError,\n getUpdateSubscriptionsError: state.subscriptions.getUpdateError,\n getUpdateShippingAddressError: state.shippingStrategies.getUpdateAddressError,\n getDeleteConsignmentError: state.consignments.getDeleteError,\n getUpdateConsignmentError: state.consignments.getUpdateError,\n getCreateConsignmentsError: state.consignments.getCreateError,\n getInitializeShippingError: state.shippingStrategies.getInitializeError,\n getApplyStoreCreditError: state.storeCredit.getApplyError,\n getApplyCouponError: state.coupons.getApplyError,\n getRemoveCouponError: state.coupons.getRemoveError,\n getApplyGiftCertificateError: state.giftCertificates.getApplyError,\n getRemoveGiftCertificateError: state.giftCertificates.getRemoveError,\n getLoadInstrumentsError: state.instruments.getLoadError,\n getDeleteInstrumentError: state.instruments.getDeleteError,\n getLoadConfigError: state.config.getLoadError,\n getSignInEmailError: state.signInEmail.getSendError,\n getCreateCustomerAccountError: state.customer.getCreateAccountError,\n getCreateCustomerAddressError: state.customer.getCreateAddressError,\n getPickupOptionsError: state.pickupOptions.getLoadError,\n getLoadExtensionsError: state.extensions.getLoadError,\n };\n\n return {\n getError: getError(selector),\n ...selector,\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for checking the statuses of various asynchronous actions related\n * to checkout.\n *\n * This object has a set of getters that return true if an action is in\n * progress. For example, you can check whether a customer is submitting an\n * order and waiting for the request to complete.\n */\nexport default interface CheckoutStoreStatusSelector {\n /**\n * Checks whether any checkout action is pending.\n *\n * @returns True if there is a pending action, otherwise false.\n */\n isPending(): boolean;\n\n /**\n * Checks whether the current checkout is loading.\n *\n * @returns True if the current checkout is loading, otherwise false.\n */\n isLoadingCheckout(): boolean;\n\n /**\n * Checks whether the current checkout is being updated.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isUpdatingCheckout(): boolean;\n\n /**\n * Checks whether spam check is executing.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isExecutingSpamCheck(): boolean;\n\n /**\n * Checks whether the current order is submitting.\n *\n * @returns True if the current order is submitting, otherwise false.\n */\n isSubmittingOrder(): boolean;\n\n /**\n * Checks whether the current order is finalizing.\n *\n * @returns True if the current order is finalizing, otherwise false.\n */\n isFinalizingOrder(): boolean;\n\n /**\n * Checks whether the current order is loading.\n *\n * @returns True if the current order is loading, otherwise false.\n */\n isLoadingOrder(): boolean;\n\n /**\n * Checks whether the current cart is loading.\n *\n * @returns True if the current cart is loading, otherwise false.\n */\n isLoadingCart(): boolean;\n\n /**\n * Checks whether billing countries are loading.\n *\n * @returns True if billing countries are loading, otherwise false.\n */\n isLoadingBillingCountries(): boolean;\n\n /**\n * Checks whether shipping countries are loading.\n *\n * @returns True if shipping countries are loading, otherwise false.\n */\n isLoadingShippingCountries(): boolean;\n\n /**\n * Checks whether payment methods are loading.\n *\n * @returns True if payment methods are loading, otherwise false.\n */\n isLoadingPaymentMethods(): boolean;\n\n /**\n * Checks whether a specific or any payment method is loading.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is loading.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is loading, otherwise false.\n */\n isLoadingPaymentMethod(methodId?: string): boolean;\n\n /**\n * Checks whether a specific or any payment method is initializing.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is initializing.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is initializing, otherwise false.\n */\n isInitializingPayment(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing in.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing in using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing in the\n * current customer.\n * @returns True if the customer is signing in, otherwise false.\n */\n isSigningIn(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing out.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing out using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing out the\n * current customer.\n * @returns True if the customer is signing out, otherwise false.\n */\n isSigningOut(methodId?: string): boolean;\n\n /**\n * Checks whether the customer step is initializing.\n *\n * If an ID is provided, the method also checks whether the customer step is\n * initializing using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for initializing the\n * customer step of checkout.\n * @returns True if the customer step is initializing, otherwise false.\n */\n isInitializingCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether a wallet button is initialized.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the wallet button method is initialized, otherwise false.\n */\n isInitializedCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is executing payment method checkout.\n *\n * If an ID is provided, the method also checks whether the customer is\n * executing payment method checkout using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for continuing the\n * current customer.\n * @returns True if the customer is executing payment method checkout, otherwise false.\n */\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n\n /**\n * Checks whether shipping options are loading.\n *\n * @returns True if shipping options are loading, otherwise false.\n */\n isLoadingShippingOptions(): boolean;\n\n /**\n * Checks whether a shipping option is being selected.\n *\n * A consignment ID should be provided when checking if a shipping option\n * is being selected for a specific consignment, otherwise it will check\n * for all consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if selecting a shipping option, otherwise false.\n */\n isSelectingShippingOption(consignmentId?: string): boolean;\n\n /**\n * Checks whether the billing address is being updated.\n *\n * @returns True if updating their billing address, otherwise false.\n */\n isUpdatingBillingAddress(): boolean;\n\n /**\n * Checks whether the shopper is continuing out as a guest.\n *\n * @returns True if continuing as guest, otherwise false.\n */\n isContinuingAsGuest(): boolean;\n\n /**\n * Checks the shipping address is being updated.\n *\n * @returns True if updating their shipping address, otherwise false.\n */\n isUpdatingShippingAddress(): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if updating consignment(s), otherwise false.\n */\n isUpdatingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being deleted.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if deleting consignment(s), otherwise false.\n */\n isDeletingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @returns True if creating consignments, otherwise false.\n */\n isCreatingConsignments(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout process is initializing.\n *\n * If an identifier is provided, the method also checks whether the shipping\n * step is initializing using a specific shipping method with the same\n * identifier.\n *\n * @param methodId - The identifer of the initialization method to check.\n * @returns True if the shipping step is initializing, otherwise false.\n */\n isInitializingShipping(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is applying a coupon code.\n *\n * @returns True if applying a coupon code, otherwise false.\n */\n isApplyingCoupon(): boolean;\n\n /**\n * Checks whether the current customer is applying store credit.\n *\n * @returns True if applying store credit, otherwise false.\n */\n isApplyingStoreCredit(): boolean;\n\n /**\n * Checks whether the current customer is removing a coupon code.\n *\n * @returns True if removing a coupon code, otherwise false.\n */\n isRemovingCoupon(): boolean;\n\n /**\n * Checks whether a sign-in email is being sent.\n *\n * @returns True if sending a sign-in email, otherwise false\n */\n isSendingSignInEmail(): boolean;\n\n /**\n * Checks whether the current customer is applying a gift certificate.\n *\n * @returns True if applying a gift certificate, otherwise false.\n */\n isApplyingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer is removing a gift certificate.\n *\n * @returns True if removing a gift certificate, otherwise false.\n */\n isRemovingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer's payment instruments are loading.\n *\n * @returns True if payment instruments are loading, otherwise false.\n */\n isLoadingInstruments(): boolean;\n\n /**\n * Checks whether the current customer is deleting a payment instrument.\n *\n * @returns True if deleting a payment instrument, otherwise false.\n */\n isDeletingInstrument(instrumentId?: string): boolean;\n\n /**\n * Checks whether the checkout configuration of a store is loading.\n *\n * @returns True if the configuration is loading, otherwise false.\n */\n isLoadingConfig(): boolean;\n\n /**\n * Checks whether the customer step of a checkout is in a pending state.\n *\n * The customer step is considered to be pending if it is in the process of\n * initializing, signing in, signing out, and/or interacting with a customer\n * widget.\n *\n * @returns True if the customer step is pending, otherwise false.\n */\n isCustomerStepPending(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout is in a pending state.\n *\n * The shipping step is considered to be pending if it is in the process of\n * initializing, updating address, selecting a shipping option, and/or\n * interacting with a shipping widget.\n *\n * @returns True if the shipping step is pending, otherwise false.\n */\n isShippingStepPending(): boolean;\n\n /**\n * Checks whether the payment step of a checkout is in a pending state.\n *\n * The payment step is considered to be pending if it is in the process of\n * initializing, submitting an order, finalizing an order, and/or\n * interacting with a payment widget.\n *\n * @returns True if the payment step is pending, otherwise false.\n */\n isPaymentStepPending(): boolean;\n\n /**\n * Checks whether the subscriptions are being updated.\n *\n * @returns True if updating subscriptions, otherwise false.\n */\n isUpdatingSubscriptions(): boolean;\n\n /**\n * Checks whether a customer account is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAccount(): boolean;\n\n /**\n * Checks whether a customer address is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAddress(): boolean;\n\n /**\n * Checks whether pickup options are loading.\n *\n * @returns True if pickup options are loading, otherwise false.\n */\n isLoadingPickupOptions(): boolean;\n}\n\nexport type CheckoutStoreStatusSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreStatusSelector;\n\nexport function createCheckoutStoreStatusSelectorFactory(): CheckoutStoreStatusSelectorFactory {\n const isPending = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n return (\n Object.keys(selector) as Array>\n ).some((key) => selector[key]());\n },\n );\n\n const isSelectingShippingOption = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ consignments }: InternalCheckoutSelectors) => consignments.isUpdatingShippingOption,\n (isSelectingOption, isUpdatingShippingOption) => (consignmentId?: string) => {\n return isSelectingOption() || isUpdatingShippingOption(consignmentId);\n },\n );\n\n const isCustomerStepPending = createSelector(\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isInitializing,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningIn,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningOut,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isExecutingPaymentMethodCheckout,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isWidgetInteracting,\n (\n isInitializing,\n isSigningIn,\n isSigningOut,\n isExecutingPaymentMethodCheckout,\n isWidgetInteracting,\n ) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isSigningIn(methodId) ||\n isSigningOut(methodId) ||\n isExecutingPaymentMethodCheckout(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isShippingStepPending = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isInitializing,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isUpdatingAddress,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.isWidgetInteracting,\n (isInitializing, isUpdatingAddress, isSelectingOption, isWidgetInteracting) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isUpdatingAddress(methodId) ||\n isSelectingOption(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isPaymentStepPending = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isInitializing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isFinalizing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isWidgetInteracting,\n (isInitializing, isExecuting, isFinalizing, isWidgetInteracting) => (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isExecuting(methodId) ||\n isFinalizing(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isSubmittingOrder = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ checkout }: InternalCheckoutSelectors) => checkout.isExecutingSpamCheck, // Remove this when CheckoutService#initializeSpamProtection is deprecated\n (isExecuting, isExecutingSpamCheck) => (methodId?: string) => {\n return isExecuting(methodId) || isExecutingSpamCheck();\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreStatusSelector => {\n const selector = {\n isLoadingCheckout: state.checkout.isLoading,\n isUpdatingCheckout: state.checkout.isUpdating,\n isExecutingSpamCheck: state.checkout.isExecutingSpamCheck,\n isSubmittingOrder: isSubmittingOrder(state),\n isFinalizingOrder: state.paymentStrategies.isFinalizing,\n isLoadingOrder: state.order.isLoading,\n isLoadingCart: state.cart.isLoading,\n isLoadingBillingCountries: state.countries.isLoading,\n isLoadingShippingCountries: state.shippingCountries.isLoading,\n isLoadingPaymentMethods: state.paymentMethods.isLoading,\n isLoadingPaymentMethod: state.paymentMethods.isLoadingMethod,\n isInitializingPayment: state.paymentStrategies.isInitializing,\n isSigningIn: state.customerStrategies.isSigningIn,\n isSigningOut: state.customerStrategies.isSigningOut,\n isExecutingPaymentMethodCheckout:\n state.customerStrategies.isExecutingPaymentMethodCheckout,\n isInitializingCustomer: state.customerStrategies.isInitializing,\n isInitializedCustomer: state.customerStrategies.isInitialized,\n isLoadingShippingOptions: state.consignments.isLoadingShippingOptions,\n isSelectingShippingOption: isSelectingShippingOption(state),\n isUpdatingBillingAddress: state.billingAddress.isUpdating,\n isUpdatingSubscriptions: state.subscriptions.isUpdating,\n isCreatingCustomerAccount: state.customer.isCreatingCustomerAccount,\n isCreatingCustomerAddress: state.customer.isCreatingCustomerAddress,\n isContinuingAsGuest: state.billingAddress.isContinuingAsGuest,\n isUpdatingShippingAddress: state.shippingStrategies.isUpdatingAddress,\n isUpdatingConsignment: state.consignments.isUpdating,\n isDeletingConsignment: state.consignments.isDeleting,\n isCreatingConsignments: state.consignments.isCreating,\n isInitializingShipping: state.shippingStrategies.isInitializing,\n isApplyingStoreCredit: state.storeCredit.isApplying,\n isApplyingCoupon: state.coupons.isApplying,\n isRemovingCoupon: state.coupons.isRemoving,\n isApplyingGiftCertificate: state.giftCertificates.isApplying,\n isRemovingGiftCertificate: state.giftCertificates.isRemoving,\n isLoadingInstruments: state.instruments.isLoading,\n isDeletingInstrument: state.instruments.isDeleting,\n isLoadingConfig: state.config.isLoading,\n isSendingSignInEmail: state.signInEmail.isSending,\n isCustomerStepPending: isCustomerStepPending(state),\n isShippingStepPending: isShippingStepPending(state),\n isPaymentStepPending: isPaymentStepPending(state),\n isLoadingPickupOptions: state.pickupOptions.isLoading,\n };\n\n return {\n isPending: isPending(selector),\n ...selector,\n };\n });\n}\n","import {\n CheckoutSelectors,\n createCheckoutStoreErrorSelectorFactory,\n createCheckoutStoreSelectorFactory,\n createCheckoutStoreStatusSelectorFactory,\n InternalCheckoutSelectors,\n} from '../checkout';\n\nexport type CheckoutSelectorsFactory = (selectors: InternalCheckoutSelectors) => CheckoutSelectors;\n\nexport function createCheckoutSelectorsFactory(): CheckoutSelectorsFactory {\n const createCheckoutStoreSelector = createCheckoutStoreSelectorFactory();\n const createCheckoutStoreErrorSelector = createCheckoutStoreErrorSelectorFactory();\n const createCheckoutStoreStatusSelector = createCheckoutStoreStatusSelectorFactory();\n\n return (selectors: InternalCheckoutSelectors) => {\n const data = createCheckoutStoreSelector(selectors);\n const errors = createCheckoutStoreErrorSelector(selectors);\n const statuses = createCheckoutStoreStatusSelector(selectors);\n\n return {\n data,\n errors,\n statuses,\n };\n };\n}\n\nexport default function createCheckoutSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutSelectors {\n return createCheckoutSelectorsFactory()(selectors);\n}\n","import { CheckoutSelectors } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\n\nimport { ExtensionEventBroadcaster } from './extension-event-broadcaster';\nimport { ExtensionEventType } from './extension-events';\nimport { ExtensionMessenger } from './extension-messenger';\nimport { subscribeConsignmentsChange } from './subscribers';\n\nexport function createExtensionEventBroadcaster(\n store: DataStoreProjection,\n messenger: ExtensionMessenger,\n): ExtensionEventBroadcaster {\n const subscribers = {\n [ExtensionEventType.ConsignmentsChanged]: subscribeConsignmentsChange,\n };\n\n return new ExtensionEventBroadcaster(store, messenger, subscribers);\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport {\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from '../payment/strategies/braintree';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createCustomerStrategyRegistryV2 from './create-customer-strategy-registry-v2';\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport CustomerStrategyActionCreator from './customer-strategy-action-creator';\nimport { CustomerStrategy } from './strategies';\nimport { BraintreeVisaCheckoutCustomerStrategy } from './strategies/braintree';\nimport { DefaultCustomerStrategy } from './strategies/default';\nimport { MasterpassCustomerStrategy } from './strategies/masterpass';\nimport { SquareCustomerStrategy } from './strategies/square';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n locale: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const formPoster = createFormPoster();\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n createSpamProtection(scriptLoader),\n new SpamProtectionRequestSender(requestSender),\n );\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n );\n\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n\n registry.register(\n 'braintreevisacheckout',\n () =>\n new BraintreeVisaCheckoutCustomerStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n new CustomerStrategyActionCreator(registry, customerRegistryV2),\n remoteCheckoutActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n formPoster,\n ),\n );\n\n registry.register(\n 'squarev2',\n () =>\n new SquareCustomerStrategy(\n store,\n new RemoteCheckoutActionCreator(remoteCheckoutRequestSender, checkoutActionCreator),\n ),\n );\n\n registry.register(\n 'masterpass',\n () =>\n new MasterpassCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register('default', () => new DefaultCustomerStrategy(store, customerActionCreator));\n\n return registry;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader, getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { StorefrontPaymentRequestSender } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport {\n createSpamProtection,\n GoogleRecaptcha,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createPaymentStrategyRegistryV2 from './create-payment-strategy-registry-v2';\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentMethodActionCreator from './payment-method-action-creator';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyActionCreator from './payment-strategy-action-creator';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { BarclaysPaymentStrategy } from './strategies/barclays';\nimport { BNZPaymentStrategy } from './strategies/bnz';\nimport {\n BraintreeCreditCardPaymentStrategy,\n BraintreeVenmoPaymentStrategy,\n BraintreeVisaCheckoutPaymentStrategy,\n createBraintreePaymentProcessor,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from './strategies/braintree';\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlowV2,\n} from './strategies/cardinal';\nimport { CBAMPGSPaymentStrategy, CBAMPGSScriptLoader } from './strategies/cba-mpgs';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport { MasterpassPaymentStrategy, MasterpassScriptLoader } from './strategies/masterpass';\nimport { OpyPaymentStrategy, OpyScriptLoader } from './strategies/opy';\nimport { PaypalExpressPaymentStrategy, PaypalScriptLoader } from './strategies/paypal';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\nimport { WepayPaymentStrategy, WepayRiskClient } from './strategies/wepay';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n spamProtection: GoogleRecaptcha,\n locale: string,\n) {\n const registry = new PaymentStrategyRegistry({\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n const scriptLoader = getScriptLoader();\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(paymentIntegrationService);\n const braintreePaymentProcessor = createBraintreePaymentProcessor(scriptLoader);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n new SpamProtectionRequestSender(requestSender),\n );\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n checkoutValidator,\n );\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n const paymentActionCreator = new PaymentActionCreator(\n paymentRequestSender,\n orderActionCreator,\n paymentRequestTransformer,\n paymentHumanVerificationHandler,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentStrategyActionCreator = new PaymentStrategyActionCreator(\n registry,\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n );\n const formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n registry.register(\n PaymentStrategyType.BARCLAYS,\n () =>\n new BarclaysPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE,\n () =>\n new BraintreeCreditCardPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), window),\n window,\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VISA_CHECKOUT,\n () =>\n new BraintreeVisaCheckoutPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CBA_MPGS,\n () =>\n new CBAMPGSPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n paymentMethodActionCreator,\n new CBAMPGSScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CONVERGE,\n () =>\n new ConvergePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ,\n () =>\n new BNZPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.MASTERPASS,\n () =>\n new MasterpassPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.OPY,\n () =>\n new OpyPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n new OpyScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS_CREDIT,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PPSDK,\n () =>\n new PPSDKStrategy(\n store,\n orderActionCreator,\n createSubStrategyRegistry(\n store,\n orderActionCreator,\n requestSender,\n stepHandler,\n hostedFormFactory,\n ),\n new PaymentResumer(requestSender, stepHandler),\n new BrowserStorage('PPSDK'),\n ),\n );\n\n registry.register(\n PaymentStrategyType.WE_PAY,\n () =>\n new WepayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n return registry;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport default function createBraintreePaymentProcessor(scriptLoader: ScriptLoader) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, window);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n const braintreeHostedForm = new BraintreeHostedForm(braintreeSDKCreator);\n\n return new BraintreePaymentProcessor(braintreeSDKCreator, braintreeHostedForm);\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BraintreeHostWindow,\n BraintreeIntegrationService,\n BraintreeScriptLoader,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n createPayPalCommerceFastlaneUtils,\n createPayPalCommerceSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { PaymentProviderCustomerActionCreator } from '../payment-provider-customer';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport ConsignmentActionCreator from './consignment-action-creator';\nimport ConsignmentRequestSender from './consignment-request-sender';\nimport ShippingStrategyActionCreator from './shipping-strategy-action-creator';\nimport { ShippingStrategy } from './strategies';\nimport { AmazonPayV2ShippingStrategy } from './strategies/amazon-pay-v2';\nimport { BraintreeFastlaneShippingStrategy } from './strategies/braintree';\nimport { DefaultShippingStrategy } from './strategies/default';\nimport { PayPalCommerceFastlaneShippingStrategy } from './strategies/paypal-commerce';\nimport { StripeUPEShippingStrategy } from './strategies/stripe-upe';\n\nexport default function createShippingStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n): Registry {\n const registry = new Registry();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const consignmentRequestSender = new ConsignmentRequestSender(requestSender);\n const consignmentActionCreator = new ConsignmentActionCreator(\n consignmentRequestSender,\n checkoutRequestSender,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const scriptLoader = getScriptLoader();\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n );\n const braintreeHostWindow: BraintreeHostWindow = window;\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2ShippingStrategy(\n store,\n consignmentActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n createAmazonPayV2PaymentProcessor(),\n new ShippingStrategyActionCreator(registry),\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPEShippingStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n consignmentActionCreator,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n 'braintreeacceleratedcheckout',\n () =>\n new BraintreeFastlaneShippingStrategy(\n store,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n new PaymentProviderCustomerActionCreator(),\n new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n ),\n ),\n );\n\n registry.register(\n 'paypalcommerceacceleratedcheckout',\n () =>\n new PayPalCommerceFastlaneShippingStrategy(\n store,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n new PaymentProviderCustomerActionCreator(),\n createPayPalCommerceSdk(),\n createPayPalCommerceFastlaneUtils(),\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\n}\n","export interface RootCacheKeyMap {\n maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n maps: ChildCacheKeyMap[];\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n usedCount: number;\n value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'parentMap');\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport {\n ChildCacheKeyMap,\n IntermediateCacheKeyMap,\n isRootCacheKeyMap,\n isTerminalCacheKeyMap,\n RootCacheKeyMap,\n TerminalCacheKeyMap,\n} from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n maxSize?: number;\n onExpire?(key: string): void;\n isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n index: number;\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n private _lastId = 0;\n private _map: RootCacheKeyMap = { maps: [] };\n private _usedMaps: TerminalCacheKeyMap[] = [];\n private _options: Required;\n\n constructor(options?: CacheKeyResolverOptions) {\n this._options = {\n maxSize: 0,\n isEqual: shallowEqual,\n onExpire: noop,\n ...options,\n };\n }\n\n getKey(...args: any[]): string {\n const result = this._resolveMap(...args);\n const { index, parentMap } = result;\n let { map } = result;\n\n if (map && map.cacheKey) {\n map.usedCount++;\n } else {\n map = this._generateMap(parentMap, args.slice(index));\n }\n\n // Keep track of the least used map so we can remove it if the size of\n // the stack exceeds the maximum size.\n this._removeLeastUsedMap(map);\n\n return map.cacheKey;\n }\n\n getUsedCount(...args: any[]): number {\n const { map } = this._resolveMap(...args);\n\n return map ? map.usedCount : 0;\n }\n\n private _resolveMap(...args: any[]): ResolveResult {\n let index = 0;\n let parentMap = this._map;\n\n // Traverse the tree to find the linked list of maps that match the\n // arguments of the call. Each intermediate or terminal map contains a\n // value that could be used to match with the arguments. The last map in\n // the list (the terminal) should contain a cache key. If it can does\n // not exist, we will return a falsy value so that the caller could\n // handle and generate a new cache key.\n while (parentMap.maps.length) {\n let isMatched = false;\n\n for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n const map = parentMap.maps[mapIndex];\n\n if (!this._options.isEqual(map.value, args[index])) {\n continue;\n }\n\n // Move the most recently used map to the top of the stack for\n // quicker access\n parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n if (\n (args.length === 0 || index === args.length - 1) &&\n isTerminalCacheKeyMap(map)\n ) {\n return { index, map, parentMap };\n }\n\n isMatched = true;\n parentMap = map;\n index++;\n\n break;\n }\n\n if (!isMatched) {\n break;\n }\n }\n\n return { index, parentMap };\n }\n\n private _generateMap(\n parent: RootCacheKeyMap | IntermediateCacheKeyMap,\n args: any[],\n ): TerminalCacheKeyMap {\n let index = 0;\n let parentMap = parent;\n let map: IntermediateCacheKeyMap;\n\n do {\n map = {\n maps: [],\n parentMap,\n usedCount: 1,\n value: args[index],\n };\n\n // Continue to build the tree of maps so that it could be resolved\n // next time when the function is called with the same set of\n // arguments.\n parentMap.maps.unshift(map);\n\n parentMap = map;\n index++;\n } while (index < args.length);\n\n const terminalMap = map as TerminalCacheKeyMap;\n\n terminalMap.cacheKey = `${++this._lastId}`;\n\n return terminalMap;\n }\n\n private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n if (!this._options.maxSize) {\n return;\n }\n\n const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n this._usedMaps.splice(index === -1 ? 0 : index, index === -1 ? 0 : 1, recentlyUsedMap);\n\n if (this._usedMaps.length <= this._options.maxSize) {\n return;\n }\n\n const map = this._usedMaps.pop();\n\n if (!map) {\n return;\n }\n\n this._removeMap(map);\n this._options.onExpire(map.cacheKey);\n }\n\n private _removeMap(map: ChildCacheKeyMap): void {\n if (!map.parentMap) {\n return;\n }\n\n map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n if (isRootCacheKeyMap(map.parentMap)) {\n return;\n }\n\n this._removeMap(map.parentMap);\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\n\nimport { bindDecorator } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CacheKeyResolver, isEqual, isPrivate } from '../utility';\n\n/**\n * Decorates a class by patching all of its methods to cache their return values\n * and return them if they are called again with the same set of parameters. The\n * decorator also binds all the methods to the calling instance so it can be\n * destructed.\n */\nexport default function selectorDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n selectorMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\nfunction selectorMethodDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let resolver = new CacheKeyResolver();\n let method = descriptor.value;\n let memoizedMethod = memoize(method);\n\n return bindDecorator(target, key, {\n get() {\n const value = ((...args: any[]) => {\n const cachedValue = memoizedMethod.call(this, ...args);\n\n if (resolver.getUsedCount(...args) === 1) {\n return cachedValue;\n }\n\n const newValue = method.call(this, ...args);\n\n if (isEqual(newValue, cachedValue, { keyFilter: (key) => !isPrivate(key) })) {\n return cachedValue;\n }\n\n memoizedMethod.cache.set(resolver.getKey(...args), newValue);\n\n return newValue;\n }) as T;\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n set(value) {\n resolver = new CacheKeyResolver();\n method = value;\n memoizedMethod = memoize(method);\n },\n });\n}\n\nexport type Constructor = new (...args: any[]) => T;\ntype Method = (...args: any[]) => any;\n","export default function isPrivate(key: string): boolean {\n return `${key}`.indexOf('$$') === 0 || `${key}`.indexOf('_') === 0;\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonErrorSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n getInitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getInitializeError(methodId);\n }\n\n getDeinitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getDeinitializeError(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonStatusSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n isInitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isInitializing(methodId);\n }\n\n isDeinitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isDeinitializing(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\n\nimport CheckoutButtonErrorSelector from './checkout-button-error-selector';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStatusSelector from './checkout-button-status-selector';\n\nexport default function createCheckoutButtonSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutButtonSelectors {\n const errors = new CheckoutButtonErrorSelector(selectors);\n const statuses = new CheckoutButtonStatusSelector(selectors);\n\n return {\n errors,\n statuses,\n };\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../checkout';\nimport { isElementId, setUniqueElementId } from '../common/dom';\n\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonSelectors from './create-checkout-button-selectors';\n\n@bind\nexport default class CheckoutButtonInitializer {\n private _state: CheckoutButtonSelectors;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _buttonStrategyActionCreator: CheckoutButtonStrategyActionCreator,\n ) {\n this._state = createCheckoutButtonSelectors(this._store.getState());\n\n this._store.subscribe((state) => {\n this._state = createCheckoutButtonSelectors(state);\n });\n }\n\n /**\n * Returns a snapshot of the current state.\n *\n * The method returns a new instance every time there is a change in the\n * state. You can query the state by calling any of its getter methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.errors.getInitializeButtonError());\n * console.log(state.statuses.isInitializingButton());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutButtonSelectors {\n return this._state;\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the current state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.statuses.isInitializingButton());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.errors.getInitializeButtonError();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.errors.getInitializeButtonError())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutButtonSelectors) => void,\n ...filters: Array<(state: CheckoutButtonSelectors) => any>\n ): () => void {\n return this._store.subscribe(\n () => subscriber(this.getState()),\n (state) => state.checkoutButton.getState(),\n ...filters.map(\n (filter) => (state: InternalCheckoutSelectors) =>\n filter(createCheckoutButtonSelectors(state)),\n ),\n );\n }\n\n /**\n * Initializes the checkout button of a payment method.\n *\n * When the checkout button is initialized, it will be inserted into the DOM,\n * ready to be interacted with by the customer.\n *\n * ```js\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * containerId: 'checkoutButton',\n * braintreepaypal: {\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n initializeButton(options: CheckoutButtonInitializeOptions): Promise {\n const containerIds = isElementId(options.containerId)\n ? [options.containerId]\n : setUniqueElementId(options.containerId, `${options.methodId}-container`);\n\n return Promise.all(\n containerIds.map((containerId) => {\n const action = this._buttonStrategyActionCreator.initialize({\n ...options,\n containerId,\n });\n const queueId = `checkoutButtonStrategy:${options.methodId}:${containerId}`;\n\n return this._store.dispatch(action, { queueId });\n }),\n ).then(() => this.getState());\n }\n\n /**\n * De-initializes the checkout button by performing any necessary clean-ups.\n *\n * ```js\n * await service.deinitializeButton({\n * methodId: 'braintreepaypal',\n * });\n * ```\n *\n * @param options - Options for deinitializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n deinitializeButton(options: CheckoutButtonOptions): Promise {\n const action = this._buttonStrategyActionCreator.deinitialize(options);\n const queueId = `checkoutButtonStrategy:${options.methodId}`;\n\n return this._store.dispatch(action, { queueId }).then(() => this.getState());\n }\n}\n","/* eslint-disable no-useless-escape */\nexport default function isElementId(id: string): boolean {\n return /^\\w[\\w\\-\\:\\.]*$/.test(id);\n}\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nexport default function setUniqueElementId(selector: string, idPrefix: string): string[] {\n const containers = document.querySelectorAll(selector);\n\n if (!containers.length) {\n throw new InvalidArgumentError(\n `Unable to find any element with the specified selector: ${selector}`,\n );\n }\n\n return Array.prototype.slice.call(containers).map((container: HTMLElement) => {\n if (!container.id) {\n container.id = uniqueId(idPrefix);\n }\n\n return container.id;\n });\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutButtonStrategy as CheckoutButtonStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator } from '../payment';\n\nimport {\n CheckoutButtonActionType,\n DeinitializeButtonAction,\n InitializeButtonAction,\n} from './checkout-button-actions';\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonRegistryV2 from './checkout-button-strategy-registry-v2';\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\n\nexport default class CheckoutButtonStrategyActionCreator {\n constructor(\n private _registry: Registry,\n private _registryV2: CheckoutButtonRegistryV2,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n initialize(\n options: CheckoutButtonInitializeOptions,\n ): ThunkAction {\n return (store) => {\n const meta = {\n methodId: options.methodId,\n containerId: options.containerId,\n };\n\n if (\n store.getState().checkoutButton.isInitialized(options.methodId, options.containerId)\n ) {\n return empty();\n }\n\n const paymentMethodRequestParams = options.currencyCode\n ? { params: { currencyCode: options.currencyCode } }\n : {};\n\n const paymentMethodRequestOptions = {\n ...paymentMethodRequestParams,\n timeout: options.timeout,\n useCache: true,\n };\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.InitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n this._paymentMethodActionCreator.loadPaymentMethod(\n options.methodId,\n paymentMethodRequestOptions,\n )(store),\n defer(() =>\n this._getStrategy(options.methodId)\n .initialize(options)\n .then(() =>\n createAction(\n CheckoutButtonActionType.InitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutButtonActionType.InitializeButtonFailed, error, meta),\n ),\n );\n };\n }\n\n deinitialize(\n options: CheckoutButtonOptions,\n ): ThunkAction {\n return (store) => {\n const meta = { methodId: options.methodId };\n\n if (!store.getState().checkoutButton.isInitialized(options.methodId)) {\n return empty();\n }\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.DeinitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n defer(() =>\n this._getStrategy(options.methodId)\n .deinitialize()\n .then(() =>\n createAction(\n CheckoutButtonActionType.DeinitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n CheckoutButtonActionType.DeinitializeButtonFailed,\n error,\n meta,\n ),\n ),\n );\n };\n }\n\n private _getStrategy(\n methodId: CheckoutButtonMethodType,\n ): CheckoutButtonStrategy | CheckoutButtonStrategyV2 {\n let strategy: CheckoutButtonStrategy | CheckoutButtonStrategyV2;\n\n try {\n strategy = this._registryV2.get({ id: methodId });\n } catch {\n strategy = this._registry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","import { Address } from '../../../address';\n\nimport { BraintreeShippingAddressOverride } from './braintree';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '../../../payment/strategies/paypal';\n\nexport default function getValidButtonStyle(style: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height, layout, shape, size, tagline } = style;\n\n const validStyles = {\n color,\n fundingicons,\n height: getValidHeight(height),\n layout,\n shape: shape || 'rect',\n size,\n tagline,\n };\n\n return omitBy(validStyles, isNil);\n}\n\nfunction getValidHeight(height?: number): number {\n const minHeight = 25;\n const maxHeight = 55;\n\n if (typeof height !== 'number' || height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport isBraintreeError from '../../../payment/strategies/braintree/is-braintree-error';\nimport { PaypalAuthorizeData, PaypalHostWindow } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalButtonInitializeOptions } from './braintree-paypal-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypal, containerId, methodId } = options;\n const { messagingContainerId, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this._renderPayPalComponents(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, messagingContainerId, onError);\n\n this._braintreeSDKCreator.initialize(clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalComponents(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { messagingContainerId } = braintreepaypal;\n\n this._renderPayPalMessages(messagingContainerId);\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n testMode,\n );\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError, onEligibilityFailure } =\n braintreepaypal;\n const { paypal } = this._window;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const validButtonStyle = style ? getValidButtonStyle(style) : {};\n\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: validButtonStyle,\n createOrder: () =>\n this._setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n }\n } else {\n this._removeElement(containerId);\n }\n }\n\n private _renderPayPalMessages(messagingContainerId?: string): void {\n const isMessageContainerAvailable =\n messagingContainerId && Boolean(document.getElementById(messagingContainerId));\n const { paypal } = this._window;\n\n if (paypal && isMessageContainerAvailable) {\n const { checkout } = this._store.getState();\n const grandTotal = checkout.getCheckoutOrThrow().outstandingBalance;\n\n const paypalMessagesRender = paypal.Messages({\n amount: grandTotal,\n placement: 'cart',\n });\n\n paypalMessagesRender.render(`#${messagingContainerId}`);\n } else {\n this._removeElement(messagingContainerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { buyNowInitializeOptions, shippingAddress, onPaymentError } = braintreepaypal;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypal.currencyCode ?? state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onPaymentError(error);\n }\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onError(error);\n }\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n buttonContainerId: string,\n messagingContainerId?: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(buttonContainerId);\n this._removeElement(messagingContainerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","export interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n style?: MessagesStyleOptions;\n}\n\nexport interface MessagesStyleOptions {\n layout?: 'text' | 'flex';\n logo?: {\n type: 'none' | 'inline' | 'primary';\n };\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onClick?(): void;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n WHITE = 'white',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport isBraintreeError from '../../../payment/strategies/braintree/is-braintree-error';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalCreditButtonInitializeOptions } from './braintree-paypal-credit-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalCreditButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypalcredit, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypalcredit.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypalcredit.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n const { clientToken, initializationData } = paymentMethod;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: initializationData.intent,\n isCreditEnabled: initializationData.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, braintreepaypalcredit.onError);\n\n this._braintreeSDKCreator.initialize(clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError, onEligibilityFailure } =\n braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = style ? getValidButtonStyle(style) : {};\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n } else if (\n paypal.FUNDING.CREDIT &&\n onEligibilityFailure &&\n typeof onEligibilityFailure === 'function'\n ) {\n // the condition is related to paypal.FUNDING.CREDIT because when paypal.FUNDING.PAYLATER is not eligible then\n // CREDIT button should be configured and triggered to render with eligibility check\n // and if it is not eligible, then onEligibilityFailure callback should be called\n onEligibilityFailure();\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(containerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypalcredit;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypalcredit.currencyCode ??\n state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onPaymentError(error);\n }\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n if (isBraintreeError(error) || error instanceof StandardError) {\n onError(error);\n }\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n containerId: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(containerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport {\n formatLocale,\n getCallbackUrl,\n Masterpass,\n MasterpassCheckoutOptions,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class MasterpassButtonStrategy implements CheckoutButtonStrategy {\n private _masterpassClient?: Masterpass;\n private _methodId?: string;\n private _signInButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n this._methodId = methodId;\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: paymentMethod.config.testMode,\n checkoutId: paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader.load(masterpassScriptLoaderParams);\n })\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n this._signInButton = this._createSignInButton(containerId);\n });\n }\n\n deinitialize(): Promise {\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.removeEventListener('click', this._handleWalletButtonClick);\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const buttonContainer = document.getElementById(containerId);\n const state = this._store.getState();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n const storeConfig = state.config.getStoreConfig();\n\n if (!buttonContainer) {\n throw new Error('Need a container to place the button');\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new InvalidArgumentError('Unable to retrieve store configuration');\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n buttonContainer.appendChild(button);\n\n button.addEventListener('click', this._handleWalletButtonClick);\n\n return button;\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: paymentMethod.initializationData.checkoutId,\n allowedCardTypes: paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.cart.cartAmount.toString(),\n currency: checkout.cart.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('cart'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(): void {\n if (!this._masterpassClient) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n this._masterpassClient.checkout(this._createMasterpassPayload());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport { INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod } from '../../../payment';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalScriptLoader,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paypalScriptLoader: PaypalScriptLoader,\n private _formPoster: FormPoster,\n private _host: string = '',\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const paypalOptions = options.paypal;\n const state = this._store.getState();\n const paymentMethod = (this._paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n ));\n\n if (!paypalOptions) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._paypalScriptLoader\n .loadPaypal(paymentMethod.config.merchantId)\n .then((paypal) => {\n if (!paymentMethod || !paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: paypalOptions.clientId };\n\n const fundingCreditOption = paypal.FUNDING.CREDIT || 'credit';\n const allowedSources = paypalOptions.allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !paypalOptions.allowCredit ? [fundingCreditOption] : [];\n\n return paypal.Button.render(\n {\n env,\n client: clientToken,\n commit: paypalOptions.shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: {\n shape: PaypalButtonStyleShapeOption.RECT,\n ...pick(\n paypalOptions.style,\n 'layout',\n 'color',\n 'label',\n 'shape',\n 'tagline',\n 'fundingicons',\n ),\n size:\n paymentMethod.id === 'paypalexpress' &&\n paypalOptions.style?.size === 'small'\n ? PaypalButtonStyleSizeOption.RESPONSIVE\n : paypalOptions.style?.size,\n },\n payment: (_, actions) =>\n this._setupPayment(merchantId, actions, paypalOptions.onPaymentError),\n onAuthorize: (data, actions) =>\n this._tokenizePayment(\n data,\n actions,\n paypalOptions.shouldProcessPayment,\n paypalOptions.onAuthorizeError,\n ),\n },\n options.containerId,\n );\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return Promise.resolve();\n }\n\n private _setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const cart = state.cart.getCart();\n const cartId = cart ? cart.id : '';\n\n return actions.request.post(\n `${this._host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n })\n .then((res) => res.id)\n .catch((error) => {\n if (onError) {\n onError(error);\n }\n\n throw error;\n });\n }\n\n private _tokenizePayment(\n data: PaypalAuthorizeData,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n _onError?: (error: StandardError) => void, // FIXME: This parameter seems to be unused\n ): Promise {\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const methodId = this._paymentMethod.id;\n\n return actions.payment.get(data.paymentID).then((payload) => {\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(payload.payer.payer_info),\n });\n });\n }\n}\n","import { StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class AmazonPayV2ConfigCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during config creation process. Please try again later.',\n );\n\n this.name = 'AmazonPayV2ConfigCreationError';\n this.type = 'amazon_pay_v2_config_creation_error';\n }\n}\n","import { WithBuyNowFeature } from './amazon-pay-v2-button-options';\n\nexport function isWithBuyNowFeatures(options: unknown): options is WithBuyNowFeature {\n if (!(options instanceof Object)) {\n return false;\n }\n\n return 'buyNowInitializeOptions' in options;\n}\n","import {\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2InitializeOptions,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n} from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n BuyNowCartCreationError,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n getShippableItemsCount,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n WithAmazonPayV2ButtonInitializeOptions,\n WithBuyNowFeature,\n} from './amazon-pay-v2-button-options';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\nimport AmazonPayV2ConfigCreationError from './errors/amazon-pay-v2-config-creation-error';\nimport { isWithBuyNowFeatures } from './isWithBuyNowFeatures';\n\nexport default class AmazonPayV2ButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowInitializeOptions: WithBuyNowFeature['buyNowInitializeOptions'];\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private amazonPayV2ConfigRequestSender: AmazonPayV2RequestSender,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithAmazonPayV2ButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, amazonpay } = options;\n const { buttonColor } = amazonpay || {};\n\n if (!methodId || !containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const { getPaymentMethodOrThrow } = this.paymentIntegrationService.getState();\n\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n const { initializationData } = paymentMethod;\n\n await this.amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (!amazonpay) {\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n const initializeAmazonButtonOptions = isWithBuyNowFeatures(amazonpay)\n ? undefined\n : amazonpay;\n\n if (\n isWithBuyNowFeatures(amazonpay) &&\n typeof amazonpay.buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ) {\n this._buyNowInitializeOptions = amazonpay.buyNowInitializeOptions;\n this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(true);\n }\n\n this.amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this.paymentIntegrationService.getState(),\n containerId,\n methodId,\n options: initializeAmazonButtonOptions,\n placement: AmazonPayV2Placement.Cart,\n buttonColor,\n isButtonMicroTextDisabled: initializationData?.isButtonMicroTextDisabled,\n });\n\n if (this._buyNowInitializeOptions) {\n this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(\n this._getCheckoutCreationRequestConfig.bind(this),\n );\n }\n }\n\n deinitialize(): Promise {\n return this.amazonPayV2PaymentProcessor.deinitialize();\n }\n\n private async _createBuyNowCartOrThrow() {\n const buyNowCartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!buyNowCartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const buyNowCart = await this.paymentIntegrationService.createBuyNowCart(\n buyNowCartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private async _createCheckoutConfig(\n id: string,\n ): Promise> {\n try {\n const {\n body: { payload, public_key, ...rest },\n } = await this.amazonPayV2ConfigRequestSender.createCheckoutConfig(id);\n\n return {\n payloadJSON: payload,\n publicKeyId: public_key,\n ...rest,\n };\n } catch (error) {\n throw new AmazonPayV2ConfigCreationError();\n }\n }\n\n private async _getCheckoutCreationRequestConfig() {\n const buyNowCart = await this._createBuyNowCartOrThrow();\n const estimatedOrderAmount = {\n amount: String(buyNowCart.baseAmount),\n currencyCode: buyNowCart.currency.code,\n };\n const createCheckoutSessionConfig = await this._createCheckoutConfig(buyNowCart.id);\n\n return {\n createCheckoutSessionConfig,\n estimatedOrderAmount,\n productType:\n getShippableItemsCount(buyNowCart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface CheckoutConfig {\n payload: string;\n signature: string;\n public_key: string;\n}\n\nexport default class AmazonPayV2RequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createCheckoutConfig(cartId: string): Promise> {\n const body = { cartId };\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post('/api/storefront/payment/amazonpay', { headers, body });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createAmazonPayV2PaymentProcessor } from '@bigcommerce/checkout-sdk/amazon-pay-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AmazonPayV2ButtonStrategy from './amazon-pay-v2-button-strategy';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\n\nconst createAmazonPayV2ButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const requestSender = createRequestSender();\n const amazonPayV2RequestSender = new AmazonPayV2RequestSender(requestSender);\n const amazonPayV2PaymentProcessor = createAmazonPayV2PaymentProcessor();\n\n return new AmazonPayV2ButtonStrategy(\n paymentIntegrationService,\n amazonPayV2PaymentProcessor,\n amazonPayV2RequestSender,\n );\n};\n\nexport default toResolvableModule(createAmazonPayV2ButtonStrategy, [{ id: 'amazonpay' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport { BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n AddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n Checkout,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ApplePayGatewayType } from './apple-pay';\nimport ApplePayButtonInitializeOptions, {\n WithApplePayButtonInitializeOptions,\n} from './apple-pay-button-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nexport enum ButtonStyleOption {\n Black = 'black',\n White = 'white',\n WhiteBorder = 'white-border',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nconst getApplePayButtonStyle = (option?: ButtonStyleOption): Record => {\n const defaultStyle: Record = {\n backgroundPosition: '50% 50%',\n backgroundRepeat: 'no-repeat',\n backgroundSize: '100% 60%',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: '32px',\n minWidth: '90px',\n padding: '1.5rem',\n display: 'block',\n };\n\n switch (option) {\n case ButtonStyleOption.White:\n defaultStyle.backgroundColor = '#fff';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-black)';\n break;\n\n case ButtonStyleOption.WhiteBorder:\n defaultStyle.backgroundColor = '#fff';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-black)';\n defaultStyle.border = '0.5px solid #000';\n break;\n\n case ButtonStyleOption.Black:\n default:\n defaultStyle.backgroundColor = '#000';\n defaultStyle.backgroundImage = '-webkit-named-image(apple-pay-logo-white)';\n }\n\n return defaultStyle;\n};\n\nexport default class ApplePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _requiresShipping?: boolean;\n private _buyNowInitializeOptions?: ApplePayButtonInitializeOptions['buyNowInitializeOptions'];\n private _onAuthorizeCallback = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n private _braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onPaymentAuthorize, buyNowInitializeOptions, requiresShipping } = applepay;\n\n this._requiresShipping = requiresShipping;\n\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n this._onAuthorizeCallback = onPaymentAuthorize;\n\n if (!buyNowInitializeOptions) {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const cart = state.getCart();\n\n if (cart) {\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n }\n\n if (this._paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n await this._initializeBraintreeSdk();\n }\n\n this._applePayButton = this._createButton(\n containerId,\n this._paymentMethod.initializationData?.styleOption,\n );\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createButton(containerId: string, styleOption?: ButtonStyleOption): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n const button = document.createElement('div');\n\n button.setAttribute('role', 'button');\n button.setAttribute('aria-label', 'Apple Pay button');\n Object.assign(button.style, getApplePayButtonStyle(styleOption));\n\n container.appendChild(button);\n\n return button;\n }\n\n private async _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this._buyNowInitializeOptions &&\n typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody === 'function'\n ) {\n const {\n countryCode,\n currencyCode,\n merchantCapabilities,\n supportedNetworks,\n storeName,\n } = this._paymentMethod.initializationData;\n\n const request = this._getRequestWithEmptyTotal(\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n );\n\n if (this._requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n }\n\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, storeName);\n\n applePaySession.begin();\n } else {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(\n applePaySession,\n this._paymentMethod,\n config.storeProfile.storeName,\n );\n\n applePaySession.begin();\n }\n }\n\n private _getRequestWithEmptyTotal(\n countryCode: string,\n currencyCode: string,\n supportedNetworks: string[],\n merchantCapabilities: ApplePayJS.ApplePayMerchantCapability[],\n ): ApplePayJS.ApplePayPaymentRequest {\n return {\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n total: { label: '', amount: '0', type: 'pending' },\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n };\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n storeName: string,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (error) {\n throw new Error('Merchant validation failed');\n }\n };\n\n if (this._buyNowInitializeOptions && !this._requiresShipping) {\n applePaySession.onpaymentmethodselected = async () => {\n await this._createBuyNowCart();\n this._handlePaymentMethodSelected(applePaySession);\n };\n }\n\n applePaySession.onshippingcontactselected = async (event) => {\n if (this._buyNowInitializeOptions && this._requiresShipping) {\n await this._createBuyNowCart();\n }\n\n await this._handleShippingContactSelected(applePaySession, storeName, event);\n };\n\n applePaySession.onshippingmethodselected = async (event) => {\n await this._handleShippingMethodSelected(applePaySession, storeName, event);\n };\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n throw new PaymentMethodCancelledError();\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _createBuyNowCart() {\n try {\n const cartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(buyNowCart.id);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private _handlePaymentMethodSelected(applePaySession: ApplePaySession) {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n\n delete request.total.type;\n\n applePaySession.completePaymentMethodSelection({\n newTotal: request.total,\n newLineItems: request.lineItems,\n });\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping address update failed');\n }\n\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n throw new Error('Shipping options update failed');\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping option selection update failed.');\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n let deviceSessionId: string | undefined;\n\n if (paymentMethod.initializationData?.gateway === ApplePayGatewayType.BRAINTREE) {\n deviceSessionId = await this._getBraintreeDeviceData();\n }\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n deviceSessionId,\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n throw new Error('Payment cannot complete');\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n\n private async _getBraintreeDeviceData(): Promise {\n try {\n const { deviceData } = await this._braintreeSdk.getDataCollectorOrThrow();\n\n return deviceData;\n } catch (_) {\n // Don't throw an error to avoid breaking checkout flow\n }\n }\n\n private async _initializeBraintreeSdk(): Promise {\n // TODO: This is a temporary solution when we load braintree to get client token (should be fixed after PAYPAL-4122)\n await this._paymentIntegrationService.loadPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n const state = this._paymentIntegrationService.getState();\n const braintreePaymentMethod = state.getPaymentMethod(ApplePayGatewayType.BRAINTREE);\n\n if (\n !braintreePaymentMethod ||\n !braintreePaymentMethod.clientToken ||\n !braintreePaymentMethod.initializationData\n ) {\n return;\n }\n\n this._braintreeSdk.initialize(braintreePaymentMethod.clientToken);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader, BraintreeSdk } from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonStrategy from './apple-pay-button-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), window)),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import { stringifyUrl } from 'query-string';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltButtonStyleOptions,\n BoltHostWindow,\n BoltPaymentMethod,\n StyleButtonShape,\n StyleButtonSize,\n} from './bolt';\nimport { WithBoltButtonInitializeOptions } from './bolt-button-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBoltButtonInitializeOptions,\n ): Promise {\n const { bolt, containerId, methodId } = options;\n const { buyNowInitializeOptions, style } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!bolt) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bolt\" argument is not provided.`,\n );\n }\n\n const isBuyNowFlow = Boolean(buyNowInitializeOptions);\n\n if (!isBuyNowFlow) {\n throw new NotImplementedError('Only buy now flow is implemented for Bolt button');\n }\n\n if (\n !buyNowInitializeOptions?.storefrontApiToken ||\n typeof buyNowInitializeOptions.storefrontApiToken !== 'string'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.storefrontApiToken\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: BoltPaymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n config.testMode,\n developerConfig,\n 'BigCommerce',\n buyNowInitializeOptions.storefrontApiToken,\n );\n\n this.renderButton(containerId, paymentMethod, style);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n if (typeof this.boltHostWindow.BoltConnect?.setupProductPageCheckout !== 'function') {\n return;\n }\n\n this.addButtonContainer(containerId, paymentMethod, style);\n this.boltHostWindow.BoltConnect.setupProductPageCheckout();\n }\n\n private addButtonContainer(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n const container = document.getElementById(containerId);\n\n if (!container) {\n return;\n }\n\n const boltButtonContainer = document.createElement('div');\n const boltButtonObject = document.createElement('object');\n\n boltButtonContainer.setAttribute('id', 'product-page-checkout-wrapper');\n boltButtonContainer.setAttribute('class', 'bolt-button-wrapper');\n boltButtonContainer.setAttribute('style', 'display:none');\n boltButtonContainer.setAttribute('data-tid', 'product-page-checkout-wrapper');\n\n boltButtonObject.setAttribute('data', this.getBoltObjectData(paymentMethod, style));\n boltButtonObject.setAttribute('class', 'bolt-product-checkout-button');\n\n boltButtonContainer.append(boltButtonObject);\n container.innerHTML = '';\n container.append(boltButtonContainer);\n }\n\n private getBoltObjectData(\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): string {\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n const domainUrl = this.boltScriptLoader.getDomainURL(!!config.testMode, developerConfig);\n const buttonHeight = this.getButtonHeight(style?.size);\n const buttonBorderRadius = this.getButtonBorderRadius(style?.shape, buttonHeight);\n\n return stringifyUrl({\n url: `https://${domainUrl}/v1/checkout_button`,\n query: {\n publishable_key: publishableKey,\n variant: 'ppc',\n height: buttonHeight,\n border_radius: buttonBorderRadius,\n },\n });\n }\n\n private getButtonHeight(buttonSize?: StyleButtonSize): number | undefined {\n if (!buttonSize) {\n return;\n }\n\n switch (buttonSize) {\n case StyleButtonSize.Small:\n return 25;\n\n case StyleButtonSize.Large:\n return 45;\n\n case StyleButtonSize.Medium:\n default:\n return 40;\n }\n }\n\n private getButtonBorderRadius(\n buttonShape?: StyleButtonShape,\n buttonHeight?: number,\n ): number | undefined {\n if (!buttonShape) {\n return;\n }\n\n switch (buttonShape) {\n case StyleButtonShape.Pill:\n return buttonHeight ? Math.round(buttonHeight / 2) : undefined;\n\n case StyleButtonShape.Rect:\n default:\n return 4;\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltButtonStrategy from './bolt-button-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltButtonStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltButtonStrategy, [{ id: 'bolt' }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n BraintreeDataCollector,\n BraintreeSdk,\n BraintreeVisaCheckout,\n VisaCheckoutAddress,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n Address,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n LegacyAddress,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BraintreeVisaCheckoutButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const { clientToken, initializationData, config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.braintreeSdk.initialize(clientToken);\n\n const braintreeVisaCheckout = await this.braintreeSdk.getBraintreeVisaCheckout();\n\n const {\n currency: { code },\n cartAmount,\n } = state.getCartOrThrow();\n\n const visaCheckoutInstance = await this.braintreeSdk.getVisaCheckoutSdk(config.testMode);\n\n const initOptions = braintreeVisaCheckout.createInitOptions({\n paymentRequest: {\n currencyCode: code,\n subtotal: String(cartAmount),\n },\n settings: {\n shipping: {\n collectShipping: true,\n },\n },\n });\n\n this.createSignInButton(containerId);\n\n await visaCheckoutInstance.init(initOptions);\n\n visaCheckoutInstance.on('payment.success', async (payment) => {\n await this.paymentSuccess(braintreeVisaCheckout, payment);\n });\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private async paymentSuccess(\n braintreeVisaCheckout: BraintreeVisaCheckout,\n payment: VisaCheckoutPaymentSuccessPayload,\n ) {\n return Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this.braintreeSdk.getDataCollectorOrThrow(),\n ]).then(([payload, deviceData]) => {\n const state = this.paymentIntegrationService.getState();\n\n const shipping = state.getShippingAddress();\n const billing = state.getBillingAddress();\n\n const {\n shippingAddress = this.toVisaCheckoutAddress(shipping),\n billingAddress = this.toVisaCheckoutAddress(billing),\n } = payload;\n\n return this.postForm(\n {\n ...payload,\n shippingAddress,\n billingAddress,\n },\n deviceData,\n );\n });\n }\n\n private postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: JSON.stringify({\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n }),\n billing_address: JSON.stringify(this.getAddress(userEmail, billingAddress)),\n shipping_address: JSON.stringify(this.getAddress(userEmail, shippingAddress)),\n });\n }\n\n private toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return this.insertVisaCheckoutButton(container);\n }\n\n private insertVisaCheckoutButton(container: Element): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.alignItems = 'flex-end';\n\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n VisaCheckoutHostWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVisaCheckoutButtonStrategy from './braintree-visa-checkout-button-strategy';\n\nconst createBraintreeVisaCheckoutButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreeVisaCheckoutButtonStrategy\n> = (paymentIntegrationService) => {\n const hostWindow: VisaCheckoutHostWindow & BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(new BraintreeScriptLoader(getScriptLoader(), hostWindow));\n\n return new BraintreeVisaCheckoutButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVisaCheckoutButtonStrategy, [\n { id: 'braintreevisacheckout' },\n]);\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeTokenizationDetails } from './types';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeTokenizationDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeTokenizationDetails } from './types';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeTokenizationDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport {\n BraintreeError,\n BraintreeSdk,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n mapToLegacyBillingAddress,\n mapToLegacyShippingAddress,\n PaypalButtonStyleColorOption,\n PaypalStyleOptions,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n BuyNowCartCreationError,\n BuyNowCartRequestBody,\n Cart,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n DefaultCheckoutButtonHeight,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n UnsupportedBrowserError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isBraintreeError from '../is-braintree-error';\nimport { isUnsupportedBrowserError } from '../isUnsupportedBrowserError';\n\nimport { WithBraintreeVenmoInitializeOptions } from './braintree-venmo-initialize-options';\n\nconst getVenmoButtonStyle = (styles: PaypalStyleOptions): Record => {\n const { color, height } = styles;\n\n const colorParser = (c: string) => {\n if (c === PaypalButtonStyleColorOption.WHITE) {\n return '#FFFFFF';\n }\n\n return '#3D95CE';\n };\n\n return {\n backgroundColor: colorParser(color || ''),\n backgroundPosition: '50% 50%',\n backgroundSize: '80px auto',\n backgroundImage: `url(\"/app/assets/img/payment-providers/venmo-logo-${\n color === PaypalButtonStyleColorOption.WHITE\n ? PaypalButtonStyleColorOption.BLUE\n : PaypalButtonStyleColorOption.WHITE\n }.svg\")`,\n backgroundRepeat: 'no-repeat',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: `${height || DefaultCheckoutButtonHeight}px`,\n minWidth: '150px',\n height: '100%',\n width: '100%',\n border: color === PaypalButtonStyleColorOption.WHITE ? '1px solid black' : 'none',\n };\n};\n\nconst venmoButtonStyleHover = {\n backgroundColor: '#0a7fc2',\n};\n\ninterface BuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n}\n\nexport default class BraintreeVenmoButtonStrategy implements CheckoutButtonStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeSdk: BraintreeSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBraintreeVenmoInitializeOptions,\n ): Promise {\n const { braintreevenmo, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { clientToken, initializationData }: PaymentMethod = paymentMethod;\n const { paymentButtonStyles } = initializationData;\n const { cartButtonStyles } = paymentButtonStyles || {};\n const styles = braintreevenmo?.style || cartButtonStyles;\n\n if (!clientToken || !initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n this.onError = braintreevenmo?.onError || this.handleError;\n this.braintreeSdk.initialize(clientToken);\n\n try {\n const braintreeVenmoCheckout = await this.braintreeSdk.getVenmoCheckoutOrThrow();\n\n this.renderVenmoButton(\n braintreeVenmoCheckout,\n containerId,\n braintreevenmo?.buyNowInitializeOptions,\n styles,\n );\n } catch (error) {\n if (isBraintreeError(error) || isUnsupportedBrowserError(error)) {\n this.handleInitializationVenmoError(error, containerId);\n }\n }\n }\n\n async deinitialize(): Promise {\n await this.braintreeSdk.deinitialize();\n\n return Promise.resolve();\n }\n\n private handleError(error: BraintreeError) {\n throw new Error(error.message);\n }\n\n private async createBuyNowCart(\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions?.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const buyNowCart = await this.paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n return undefined;\n }\n\n private handleInitializationVenmoError(\n error: BraintreeError | UnsupportedBrowserError,\n containerId: string,\n ): void {\n this.removeVenmoContainer(containerId);\n\n return this.onError(error);\n }\n\n private removeVenmoContainer(containerId: string): void {\n const buttonContainer = document.getElementById(containerId);\n\n if (buttonContainer) {\n buttonContainer.remove();\n }\n }\n\n private renderVenmoButton(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n containerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n buttonStyles?: PaypalStyleOptions,\n ): void {\n const venmoButton = document.getElementById(containerId);\n const { color } = buttonStyles || {};\n\n if (!venmoButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n venmoButton.setAttribute('aria-label', 'Venmo');\n Object.assign(venmoButton.style, getVenmoButtonStyle(buttonStyles || {}));\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n venmoButton.addEventListener('click', async () => {\n venmoButton.setAttribute('disabled', 'true');\n\n const buyBowCart = await this.createBuyNowCart(buyNowInitializeOptions);\n\n if (braintreeVenmoCheckout.tokenize) {\n braintreeVenmoCheckout.tokenize(\n async (\n error: BraintreeError | undefined,\n payload: BraintreeTokenizePayload,\n ) => {\n venmoButton.removeAttribute('disabled');\n\n if (error) {\n this.onError(error);\n }\n\n await this.handlePostForm(payload, buyBowCart?.id);\n },\n );\n }\n });\n\n if (color === PaypalButtonStyleColorOption.BLUE) {\n venmoButton.addEventListener('mouseenter', () => {\n venmoButton.style.backgroundColor = venmoButtonStyleHover.backgroundColor;\n });\n\n venmoButton.addEventListener('mouseleave', () => {\n venmoButton.style.backgroundColor = getVenmoButtonStyle(\n buttonStyles || {},\n ).backgroundColor;\n });\n }\n }\n\n private async handlePostForm(\n payload: BraintreeTokenizePayload,\n buyNowCartId?: string,\n ): Promise {\n const { deviceData } = await this.braintreeSdk.getDataCollectorOrThrow();\n const { nonce, details } = payload;\n\n this.formPoster.postForm('/checkout.php', {\n nonce,\n provider: 'braintreevenmo',\n payment_type: 'paypal',\n device_data: deviceData,\n action: 'set_external_checkout',\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n }\n}\n","import { UnsupportedBrowserError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport function isUnsupportedBrowserError(error: unknown): error is UnsupportedBrowserError {\n return error instanceof UnsupportedBrowserError;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeVenmoButtonStrategy from './braintree-venmo-button-strategy';\n\nconst createBraintreeVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n BraintreeVenmoButtonStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const scriptLoader = getScriptLoader();\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader, braintreeHostWindow);\n\n const braintreeSdk = new BraintreeSdk(braintreeScriptLoader);\n\n return new BraintreeVenmoButtonStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeSdk,\n );\n};\n\nexport default toResolvableModule(createBraintreeVenmoButtonStrategy, [{ id: 'braintreevenmo' }]);\n","import {\n BuyNowCartCreationError,\n Cart,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n guard,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithGooglePayButtonInitializeOptions } from './google-pay-button-initialize-option';\nimport GooglePayCustomerInitializeOptions from './google-pay-customer-initialize-options';\nimport { WithGooglePayPaymentInitializeOptions } from './google-pay-payment-initialize-options';\nimport GooglePayPaymentProcessor from './google-pay-payment-processor';\nimport isGooglePayErrorObject from './guards/is-google-pay-error-object';\nimport isGooglePayKey from './guards/is-google-pay-key';\nimport {\n GooglePayBuyNowInitializeOptions,\n GooglePayInitializationData,\n GooglePayPaymentOptions,\n IntermediatePaymentData,\n NewTransactionInfo,\n ShippingOptionParameters,\n TotalPriceStatusType,\n} from './types';\n\nexport default class GooglePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentButton?: HTMLElement;\n private _methodId?: keyof WithGooglePayPaymentInitializeOptions;\n private _buyNowCart?: Cart;\n private _currencyCode?: string;\n private _buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions;\n private _countryCode?: string;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithGooglePayButtonInitializeOptions,\n ): Promise {\n if (!options.methodId || !isGooglePayKey(options.methodId)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" is not a valid key.',\n );\n }\n\n this._methodId = options.methodId;\n\n if (!options.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" is not a valid key.',\n );\n }\n\n const googlePayOptions = options[this._getMethodOrThrow()];\n\n if (!googlePayOptions) {\n throw new InvalidArgumentError('Unable to proceed without valid options.');\n }\n\n const { buyNowInitializeOptions, currencyCode, buttonColor, buttonType, onError } =\n googlePayOptions;\n\n let state = this._paymentIntegrationService.getState();\n let paymentMethod: PaymentMethod;\n\n try {\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodOrThrow());\n } catch (_e) {\n state = await this._paymentIntegrationService.loadPaymentMethod(\n this._getMethodOrThrow(),\n );\n paymentMethod = state.getPaymentMethodOrThrow(this._getMethodOrThrow());\n }\n\n this._countryCode = paymentMethod.initializationData?.storeCountry;\n\n if (buyNowInitializeOptions) {\n if (!currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.currencyCode\" argument is not provided.`,\n );\n }\n\n this._currencyCode = currencyCode;\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(),\n !!buyNowInitializeOptions,\n currencyCode,\n );\n } else {\n await this._paymentIntegrationService.loadDefaultCheckout();\n await this._googlePayPaymentProcessor.initialize(\n () => paymentMethod,\n this._getGooglePayClientOptions(),\n );\n }\n\n this._paymentButton =\n this._paymentButton ??\n this._googlePayPaymentProcessor.addPaymentButton(options.containerId, {\n buttonColor: buttonColor ?? 'default',\n buttonType: buttonType ?? 'plain',\n onClick: this._handleClick(onError),\n });\n }\n\n deinitialize(): Promise {\n this._paymentButton?.remove();\n this._paymentButton = undefined;\n this._methodId = undefined;\n\n return Promise.resolve();\n }\n\n private _handleClick(\n onError: GooglePayCustomerInitializeOptions['onError'],\n ): (event: MouseEvent) => unknown {\n return async (event: MouseEvent) => {\n event.preventDefault();\n\n try {\n if (this._buyNowInitializeOptions) {\n await this._createBuyNowCartOrThrow(this._buyNowInitializeOptions);\n } else {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._googlePayPaymentProcessor.initializeWidget();\n await this._interactWithPaymentSheet();\n } catch (error) {\n let err: unknown = error;\n\n if (isGooglePayErrorObject(error)) {\n if (error.statusCode === 'CANCELED') {\n throw new PaymentMethodCancelledError();\n }\n\n err = new PaymentMethodFailedError(JSON.stringify(error));\n }\n\n onError?.(\n new PaymentMethodFailedError(\n 'An error occurred while requesting your Google Pay payment details.',\n ),\n );\n\n throw err;\n }\n };\n }\n\n private async _interactWithPaymentSheet(): Promise {\n const response = await this._googlePayPaymentProcessor.showPaymentSheet();\n const billingAddress =\n this._googlePayPaymentProcessor.mapToBillingAddressRequestBody(response);\n const shippingAddress =\n this._googlePayPaymentProcessor.mapToShippingAddressRequestBody(response);\n const siteLink =\n window.location.pathname === '/embedded-checkout'\n ? this._paymentIntegrationService.getState().getStoreConfigOrThrow().links.siteLink\n : undefined;\n\n if (billingAddress) {\n await this._paymentIntegrationService.updateBillingAddress(billingAddress);\n }\n\n if (shippingAddress && !this._buyNowCart?.lineItems.digitalItems.length) {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n }\n\n await this._googlePayPaymentProcessor.setExternalCheckoutForm(\n this._getMethodOrThrow(),\n response,\n siteLink,\n );\n }\n\n private _getGooglePayClientOptions(): GooglePayPaymentOptions | undefined {\n return {\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n shippingAddress,\n shippingOptionData,\n }: IntermediatePaymentData): Promise => {\n const {\n availableTriggers,\n addressChangeTriggers,\n shippingOptionsChangeTriggers,\n } = this._googlePayPaymentProcessor.getCallbackTriggers();\n\n if (!availableTriggers.includes(callbackTrigger)) {\n return;\n }\n\n const availableShippingOptions = addressChangeTriggers.includes(callbackTrigger)\n ? await this._googlePayPaymentProcessor.handleShippingAddressChange(\n shippingAddress,\n )\n : undefined;\n\n if (shippingOptionsChangeTriggers.includes(callbackTrigger)) {\n await this._googlePayPaymentProcessor.handleShippingOptionChange(\n shippingOptionData.id,\n );\n }\n\n if (this._buyNowInitializeOptions) {\n return this._getBuyNowTransactionInfo(availableShippingOptions);\n }\n\n return this._getTransactionInfo(availableShippingOptions);\n },\n },\n };\n }\n\n private async _createBuyNowCartOrThrow(\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n try {\n this._buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(this._buyNowCart.id);\n } catch (error) {\n if (typeof error === 'string') {\n throw new BuyNowCartCreationError(error);\n }\n\n throw error;\n }\n }\n }\n\n private _getBuyNowTransactionInfo(availableShippingOptions?: ShippingOptionParameters) {\n if (!this._buyNowCart) {\n return;\n }\n\n const { cartAmount } = this._buyNowCart;\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n\n return {\n newTransactionInfo: {\n ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode: this._getCurrencyCodeOrThrow(),\n totalPrice: totalPrice || String(cartAmount),\n totalPriceStatus: TotalPriceStatusType.FINAL,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n }\n\n private async _getTransactionInfo(availableShippingOptions?: ShippingOptionParameters) {\n await this._paymentIntegrationService.loadCheckout();\n\n const totalPrice = this._googlePayPaymentProcessor.getTotalPrice();\n const { code: currencyCode } = this._paymentIntegrationService\n .getState()\n .getCartOrThrow().currency;\n\n return {\n newTransactionInfo: {\n ...(this._countryCode && { countryCode: this._countryCode }),\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n ...(availableShippingOptions && {\n newShippingOptionParameters: availableShippingOptions,\n }),\n };\n }\n\n private _getMethodOrThrow(): keyof WithGooglePayButtonInitializeOptions {\n return guard(\n this._methodId,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _getCurrencyCodeOrThrow(): string {\n return guard(\n this._currencyCode,\n () =>\n new InvalidArgumentError(\n 'Unable to initialize payment because \"options.currencyCode\" argument is not provided.',\n ),\n );\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n BraintreeHostWindow,\n BraintreeScriptLoader,\n BraintreeSdk,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayBraintreeGateway from '../../gateways/google-pay-braintree-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayBraintreeButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeSdk = new BraintreeSdk(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n );\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayBraintreeGateway(paymentIntegrationService, braintreeSdk),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayBraintreeButtonStrategy, [\n { id: 'googlepaybraintree' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayButtonStrategy from '../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayPaypalCommerceGateway from './google-pay-paypal-commerce-gateway';\nimport PayPalCommerceScriptLoader from './google-pay-paypal-commerce-script-loader';\n\nconst createGooglePayPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayPaypalCommerceGateway(\n paymentIntegrationService,\n new PayPalCommerceScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayPayPalCommerceButtonStrategy, [\n { id: 'googlepaypaypalcommerce' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV2ButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV2ButtonStrategy, [\n { id: 'googlepayadyenv2' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayGateway from '../../gateways/google-pay-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAdyenV3ButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayGateway('adyen', paymentIntegrationService),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayAdyenV3ButtonStrategy, [\n { id: 'googlepayadyenv3' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayAuthorizeNetGateway from '../../gateways/google-pay-authorizenet-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayAuthorizeNetButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayAuthorizeNetGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayAuthorizeNetButtonStrategy, [\n { id: 'googlepayauthorizenet' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCheckoutComGateway from '../../gateways/google-pay-checkoutcom-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCheckoutComButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) => {\n const requestSender = createRequestSender();\n\n return new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCheckoutComGateway(paymentIntegrationService, requestSender),\n requestSender,\n createFormPoster(),\n ),\n );\n};\n\nexport default toResolvableModule(createGooglePayCheckoutComButtonStrategy, [\n { id: 'googlepaycheckoutcom' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayCybersourceGateway from '../../gateways/google-pay-cybersource-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayCybersourceButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayCybersourceGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayCybersourceButtonStrategy, [\n { id: 'googlepaycybersourcev2' },\n { id: 'googlepaybnz' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayOrbitalGateway from '../../gateways/google-pay-orbital-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayOrbitalButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayOrbitalGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayOrbitalButtonStrategy, [\n { id: 'googlepayorbital' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createGooglePayScriptLoader from '../factories/create-google-pay-script-loader';\nimport GooglePayButtonStrategy from '../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../google-pay-payment-processor';\n\nimport GooglePayStripeGateway from './google-pay-stripe-gateway';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nconst createGooglePayStripeButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayStripeGateway(\n paymentIntegrationService,\n new StripeUPEScriptLoader(getScriptLoader()),\n ),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayStripeButtonStrategy, [\n { id: 'googlepaystripe' },\n { id: 'googlepaystripeupe' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayWorldpayAccessGateway from '../../gateways/google-pay-worldpayaccess-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayWorldpayAccessButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayWorldpayAccessGateway(paymentIntegrationService),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayWorldpayAccessButtonStrategy, [\n { id: 'googlepayworldpayaccess' },\n]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport GooglePayTdOnlineMartGateway from '../../gateways/google-pay-tdonlinemart-gateway';\nimport GooglePayButtonStrategy from '../../google-pay-button-strategy';\nimport GooglePayPaymentProcessor from '../../google-pay-payment-processor';\nimport createGooglePayScriptLoader from '../create-google-pay-script-loader';\n\nconst createGooglePayTdOnlineMartButtonStrategy: CheckoutButtonStrategyFactory<\n GooglePayButtonStrategy\n> = (paymentIntegrationService) =>\n new GooglePayButtonStrategy(\n paymentIntegrationService,\n new GooglePayPaymentProcessor(\n createGooglePayScriptLoader(),\n new GooglePayTdOnlineMartGateway(paymentIntegrationService, createFormPoster()),\n createRequestSender(),\n createFormPoster(),\n ),\n );\n\nexport default toResolvableModule(createGooglePayTdOnlineMartButtonStrategy, [\n { id: 'googlepaytdonlinemart' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceButtonInitializeOptions, {\n WithPayPalCommerceButtonInitializeOptions,\n} from './paypal-commerce-button-initialize-options';\n\nexport default class PayPalCommerceButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceButtonInitializeOptions,\n ): Promise {\n const { paypalcommerce, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(paypalcommerce?.buyNowInitializeOptions);\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !paypalcommerce.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof paypalcommerce.buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? paypalcommerce.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommerce: PayPalCommerceButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceButtonStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n getPaypalMessagesStylesFromBNPLConfig,\n MessagingOptions,\n PayPalBNPLConfigurationItem,\n PayPalCommerceInitializationData,\n PayPalCommerceSdk,\n PayPalMessagesSdk,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditButtonInitializeOptions, {\n WithPayPalCommerceCreditButtonInitializeOptions,\n} from './paypal-commerce-credit-button-initialize-options';\n\nexport default class PayPalCommerceCreditButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private paypalCommerceSdk: PayPalCommerceSdk,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const {\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n messagingContainerId,\n } = paypalcommercecredit || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n const state = this.paymentIntegrationService.getState();\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : state.getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\n\n const messagingContainer =\n messagingContainerId && document.getElementById(messagingContainerId);\n\n if (currencyCode && messagingContainer) {\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // TODO: update paypalBNPLConfiguration with empty array as default value when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const { paypalBNPLConfiguration } = paymentMethod.initializationData || {};\n let bannerConfiguration: PayPalBNPLConfigurationItem | undefined;\n\n if (paypalBNPLConfiguration) {\n bannerConfiguration = paypalBNPLConfiguration.find(({ id }) => id === 'cart');\n\n if (!bannerConfiguration?.status) {\n return;\n }\n\n // TODO: remove this attributes reset when content service and PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n messagingContainer.removeAttribute('data-pp-style-text-color');\n messagingContainer.removeAttribute('data-pp-style-logo-type');\n messagingContainer.removeAttribute('data-pp-style-logo-position');\n }\n\n const paypalSdk = await this.paypalCommerceSdk.getPayPalMessages(\n paymentMethod,\n currencyCode,\n );\n\n this.renderMessages(paypalSdk, messagingContainerId, bannerConfiguration);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercecredit: PayPalCommerceCreditButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete, onEligibilityFailure } =\n paypalcommercecredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.countryCode,\n postalCode: data.shippingAddress.postalCode,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n if (typeof error === 'string') {\n throw new Error(error);\n }\n\n throw error;\n }\n }\n\n private renderMessages(\n paypalMessagesSdk: PayPalMessagesSdk,\n messagingContainerId: string,\n bannerConfiguration?: PayPalBNPLConfigurationItem, // TODO: this should not be optional when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n ): void {\n const checkout = this.paymentIntegrationService.getState().getCheckoutOrThrow();\n const grandTotal = checkout.outstandingBalance;\n // TODO: default style can be removed when PROJECT-6784.paypal_commerce_bnpl_configurator experiment is rolled out to 100%\n const style = bannerConfiguration\n ? getPaypalMessagesStylesFromBNPLConfig(bannerConfiguration)\n : {\n layout: 'text',\n };\n\n const paypalMessagesOptions: MessagingOptions = {\n amount: grandTotal,\n placement: 'cart',\n style,\n };\n\n const paypalMessages = paypalMessagesSdk.Messages(paypalMessagesOptions);\n\n paypalMessages.render(`#${messagingContainerId}`);\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { createPayPalCommerceSdk } from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n createPayPalCommerceSdk(),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditButtonStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoButtonInitializeOptions, {\n WithPayPalCommerceVenmoButtonInitializeOptions,\n} from './paypal-commerce-venmo-button-initialize-options';\n\nexport default class PayPalCommerceVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceVenmoButtonInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n paypalcommercevenmo || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onEligibilityFailure } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.getValidVenmoButtonStyles(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle = this.paypalCommerceIntegrationService.getValidButtonStyle(style);\n\n if (validButtonStyle.color === StyleButtonColor.gold) {\n return {\n ...validButtonStyle,\n color: undefined,\n };\n }\n\n return validButtonStyle;\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoButtonStrategy from './paypal-commerce-venmo-button-strategy';\n\nconst createPayPalCommerceVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoButtonStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsButtonOptions, {\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n} from './paypal-commerce-alternative-methods-button-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsButtonStrategy\n implements CheckoutButtonStrategy\n{\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n ): Promise {\n const { paypalcommercealternativemethods, containerId, methodId } = options;\n const {\n apm,\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n } = paypalcommercealternativemethods || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercealternativemethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n if (!apm) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.apm\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercealternativemethods);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercealternativemethods: PayPalCommerceAlternativeMethodsButtonOptions,\n ): void {\n const { apm, buyNowInitializeOptions, style, onEligibilityFailure } =\n paypalcommercealternativemethods;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(apm);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"options.paypalcommercealternativemethods.apm\" argument is not valid funding source.`,\n );\n }\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethod',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: apm,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else if (onEligibilityFailure && typeof onEligibilityFailure === 'function') {\n onEligibilityFailure();\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsButtonStrategy from './paypal-commerce-alternative-methods-button-strategy';\n\nconst createPayPalCommerceAlternativeMethodsButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceAlternativeMethodsButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsButtonStrategy, [\n { id: 'paypalcommercealternativemethods' },\n]);\n","export interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressButtonInitializeOptions } from './paypal-express-button-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal-express-types';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalExpressScriptLoader: PaypalScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!options.paypal) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSDK = await this.paypalExpressScriptLoader.loadPaypalSDK(\n paymentMethod.config.merchantId,\n );\n\n this.renderButton(options, paypalSDK);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n paypalSDK: PaypalSDK,\n ) {\n const { containerId, methodId, paypal } = options;\n const { allowCredit, clientId, onPaymentError, shouldProcessPayment, style } = paypal;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: clientId };\n const fundingCreditOption = paypalSDK.FUNDING.CREDIT || 'credit';\n const allowedSources = allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !allowCredit ? [fundingCreditOption] : [];\n\n return paypalSDK.Button.render(\n {\n env,\n client: clientToken,\n commit: shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: this.getStyle(style),\n payment: (_, actions) => this.setupPayment(merchantId, actions, onPaymentError),\n onAuthorize: (data, actions) =>\n this.tokenizePayment(data, methodId, actions, shouldProcessPayment),\n },\n containerId,\n );\n }\n\n private getStyle(style?: Omit): PaypalStyleOptions {\n const { color, fundingicons, label, layout, shape, size, tagline } = style || {};\n\n return {\n color,\n fundingicons,\n label,\n layout,\n shape: shape || PaypalButtonStyleShapeOption.RECT,\n size: size === 'small' ? PaypalButtonStyleSizeOption.RESPONSIVE : size,\n tagline,\n };\n }\n\n private async setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n try {\n const state = await this.paymentIntegrationService.loadDefaultCheckout();\n const { id: cartId } = state.getCartOrThrow();\n const host = state.getHost() || '';\n\n const paymentRequest = await actions.request.post(\n `${host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n\n return paymentRequest.id;\n } catch (error) {\n if (onError && error instanceof StandardError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePayment(\n data: PaypalAuthorizeData,\n methodId: string,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const getPaymentData = await actions.payment.get(data.paymentID);\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: paymentMethod.id,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(getPaymentData.payer.payer_info),\n });\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalScriptLoader {\n private window: PaypalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async loadPaypalSDK(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n ...(merchantId && {\n attributes: { 'data-merchant-id': merchantId },\n }),\n };\n\n await this.scriptLoader.loadScript(scriptSrc, options);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalExpressButtonStrategy, PaypalExpressScriptLoader } from './index';\n\nconst createPaypalExpressButtonStrategy: CheckoutButtonStrategyFactory<\n PaypalExpressButtonStrategy\n> = (paymentIntegrationService) => {\n return new PaypalExpressButtonStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressButtonStrategy, [{ id: 'paypalexpress' }]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { ConfigState } from '../config';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\n\nimport CheckoutButtonInitializer from './checkout-button-initializer';\nimport CheckoutButtonInitializerOptions from './checkout-button-initializer-options';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonRegistry from './create-checkout-button-registry';\nimport createCheckoutButtonRegistryV2 from './create-checkout-button-registry-v2';\n\n/**\n * Creates an instance of `CheckoutButtonInitializer`.\n *\n * @remarks\n * ```js\n * const initializer = createCheckoutButtonInitializer();\n *\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * braintreepaypal: {\n * container: '#checkoutButton',\n * },\n * });\n * ```\n *\n * @alpha\n * Please note that `CheckoutButtonInitializer` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutButtonInitializer`.\n */\nexport default function createCheckoutButtonInitializer(\n options?: CheckoutButtonInitializerOptions,\n): CheckoutButtonInitializer {\n const { host, locale = 'en' } = options ?? {};\n\n const config: ConfigState = {\n meta: {\n host: options?.host,\n locale: options?.locale,\n },\n errors: {},\n statuses: {},\n };\n\n const store = createCheckoutStore({ config });\n const requestSender = createRequestSender({ host });\n const formPoster = createFormPoster({ host });\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createCheckoutButtonRegistryV2(paymentIntegrationService);\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, locale, host),\n registryV2,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n ),\n );\n}\n","import {\n CheckoutButtonStrategy,\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories = defaultCheckoutButtonStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry<\n CheckoutButtonStrategy,\n CheckoutButtonStrategyResolveId\n >();\n\n for (const [, createCheckoutButtonStrategy] of Object.entries(\n checkoutButtonStrategyFactories,\n )) {\n if (\n !isResolvableModule<\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId\n >(createCheckoutButtonStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCheckoutButtonStrategy.resolveIds) {\n registry.register(resolverId, () =>\n createCheckoutButtonStrategy(paymentIntegrationService),\n );\n }\n }\n\n return registry;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BraintreeScriptLoader } from '@bigcommerce/checkout-sdk/braintree-utils';\n\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { BraintreeSDKCreator } from '../payment/strategies/braintree';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport {\n BraintreePaypalButtonStrategy,\n BraintreePaypalCreditButtonStrategy,\n} from './strategies/braintree';\nimport { MasterpassButtonStrategy } from './strategies/masterpass';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\n locale: string,\n host?: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const braintreeSdkCreator = new BraintreeSDKCreator(\n new BraintreeScriptLoader(scriptLoader, window),\n );\n const cartRequestSender = new CartRequestSender(requestSender);\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalCreditButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.MASTERPASS,\n () =>\n new MasterpassButtonStrategy(\n store,\n checkoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.PAYPALEXPRESS,\n () =>\n new PaypalButtonStrategy(\n store,\n checkoutActionCreator,\n new PaypalScriptLoader(scriptLoader),\n formPoster,\n host,\n ),\n );\n\n return registry;\n}\n","import EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedContentOptions } from './iframe-content';\n\nexport enum EmbeddedCheckoutEventType {\n CheckoutComplete = 'CHECKOUT_COMPLETE',\n CheckoutError = 'CHECKOUT_ERROR',\n CheckoutLoaded = 'CHECKOUT_LOADED',\n FrameError = 'FRAME_ERROR',\n FrameLoaded = 'FRAME_LOADED',\n SignedOut = 'SIGNED_OUT',\n}\n\nexport interface EmbeddedCheckoutEventMap {\n [EmbeddedCheckoutEventType.CheckoutComplete]: EmbeddedCheckoutCompleteEvent;\n [EmbeddedCheckoutEventType.CheckoutError]: EmbeddedCheckoutErrorEvent;\n [EmbeddedCheckoutEventType.CheckoutLoaded]: EmbeddedCheckoutLoadedEvent;\n [EmbeddedCheckoutEventType.FrameError]: EmbeddedCheckoutFrameErrorEvent;\n [EmbeddedCheckoutEventType.FrameLoaded]: EmbeddedCheckoutFrameLoadedEvent;\n [EmbeddedCheckoutEventType.SignedOut]: EmbeddedCheckoutSignedOutEvent;\n}\n\nexport type EmbeddedCheckoutEvent =\n | EmbeddedCheckoutCompleteEvent\n | EmbeddedCheckoutErrorEvent\n | EmbeddedCheckoutFrameErrorEvent\n | EmbeddedCheckoutFrameLoadedEvent\n | EmbeddedCheckoutLoadedEvent\n | EmbeddedCheckoutSignedOutEvent;\n\nexport interface EmbeddedCheckoutCompleteEvent {\n type: EmbeddedCheckoutEventType.CheckoutComplete;\n}\n\nexport interface EmbeddedCheckoutErrorEvent {\n type: EmbeddedCheckoutEventType.CheckoutError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutLoadedEvent {\n type: EmbeddedCheckoutEventType.CheckoutLoaded;\n}\n\nexport interface EmbeddedCheckoutFrameErrorEvent {\n type: EmbeddedCheckoutEventType.FrameError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutFrameLoadedEvent {\n type: EmbeddedCheckoutEventType.FrameLoaded;\n payload?: EmbeddedContentOptions;\n}\n\nexport interface EmbeddedCheckoutSignedOutEvent {\n type: EmbeddedCheckoutEventType.SignedOut;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error we are not able to sign in a shopper because the provided\n * login token is invalid.\n */\nexport default class InvalidLoginTokenError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'InvalidLoginTokenError';\n this.type = 'invalid_login_token';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport enum NotEmbeddableErrorType {\n MissingContainer = 'missing_container',\n MissingContent = 'missing_content',\n UnknownError = 'unknown_error',\n}\n\n/**\n * Throw this error if we are not able to embed the checkout form as an iframe.\n * This can be due to the fact that the provided container ID is invalid, or the\n * checkout form fails to load inside the iframe. It can also be due to an\n * unknown reason.\n */\nexport default class NotEmbeddableError extends StandardError {\n constructor(\n message?: string,\n public subtype: NotEmbeddableErrorType = NotEmbeddableErrorType.UnknownError,\n ) {\n super(message || 'Unable to embed the checkout form.');\n\n this.name = 'NotEmbeddableError';\n this.type = 'not_embeddable';\n }\n}\n","import EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nexport enum EmbeddedContentEventType {\n StyleConfigured = 'STYLE_CONFIGURED',\n}\n\nexport interface EmbeddedContentEventMap {\n [EmbeddedContentEventType.StyleConfigured]: EmbeddedContentStyleConfiguredEvent;\n}\n\nexport type EmbeddedContentEvent = EmbeddedContentStyleConfiguredEvent;\n\nexport interface EmbeddedContentStyleConfiguredEvent {\n type: EmbeddedContentEventType.StyleConfigured;\n payload: EmbeddedCheckoutStyles;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { IFrameComponent, IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { InvalidLoginTokenError, NotEmbeddableError, NotEmbeddableErrorType } from './errors';\nimport { EmbeddedContentEvent, EmbeddedContentEventType } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport const ALLOW_COOKIE_ATTEMPT_INTERVAL = 10 * 60 * 1000;\nexport const IS_COOKIE_ALLOWED_KEY = 'isCookieAllowed';\nexport const LAST_ALLOW_COOKIE_ATTEMPT_KEY = 'lastAllowCookieAttempt';\n\n@bind\nexport default class EmbeddedCheckout {\n private _iframe?: IFrameComponent;\n private _isAttached: boolean;\n\n /**\n * @internal\n */\n constructor(\n private _iframeCreator: ResizableIframeCreator,\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _loadingIndicator: LoadingIndicator,\n private _requestSender: RequestSender,\n private _storage: BrowserStorage,\n private _location: Location,\n private _options: EmbeddedCheckoutOptions,\n ) {\n this._isAttached = false;\n\n if (this._options.onComplete) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutComplete,\n this._options.onComplete,\n );\n }\n\n if (this._options.onError) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutError,\n this._options.onError,\n );\n }\n\n if (this._options.onLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutLoaded,\n this._options.onLoad,\n );\n }\n\n if (this._options.onFrameLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.FrameLoaded,\n this._options.onFrameLoad,\n );\n }\n\n if (this._options.onSignOut) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.SignedOut,\n this._options.onSignOut,\n );\n }\n\n this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, () =>\n this._configureStyles(),\n );\n }\n\n attach(): Promise {\n if (this._isAttached) {\n return Promise.resolve(this);\n }\n\n this._isAttached = true;\n this._messageListener.listen();\n this._loadingIndicator.show(this._options.containerId);\n\n return this._allowCookie()\n .then(() => this._attemptLogin())\n .then((url) => this._iframeCreator.createFrame(url, this._options.containerId))\n .then((iframe) => {\n this._iframe = iframe;\n\n this._configureStyles();\n this._loadingIndicator.hide();\n })\n .catch((error) => {\n this._isAttached = false;\n\n return this._retryAllowCookie(error).catch(() => {\n this._messageListener.trigger({\n type: EmbeddedCheckoutEventType.FrameError,\n payload: error,\n });\n\n this._loadingIndicator.hide();\n\n throw error;\n });\n })\n .then(() => this);\n }\n\n detach(): void {\n if (!this._isAttached) {\n return;\n }\n\n this._isAttached = false;\n this._messageListener.stopListen();\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe.iFrameResizer.close();\n }\n }\n\n private _configureStyles(): void {\n if (!this._iframe || !this._iframe.contentWindow || !this._options.styles) {\n return;\n }\n\n this._messagePoster.setTarget(this._iframe.contentWindow);\n\n this._messagePoster.post({\n type: EmbeddedContentEventType.StyleConfigured,\n payload: this._options.styles,\n });\n }\n\n private _attemptLogin(): Promise {\n if (!/^\\/login\\/token/.test(parseUrl(this._options.url).pathname)) {\n return Promise.resolve(this._options.url);\n }\n\n return this._requestSender\n .post<{ redirectUrl: string }>(this._options.url)\n .then(({ body: { redirectUrl } }) => redirectUrl)\n .catch((response) => Promise.reject(new InvalidLoginTokenError(response)));\n }\n\n /**\n * This workaround is required for certain browsers (namely Safari) that\n * prevent session cookies to be set for a third party website unless the\n * user has recently visited such website. Therefore, before we attempt to\n * login or set an active cart in the session, we need to first redirect the\n * user to the domain of Embedded Checkout.\n */\n private _allowCookie(): Promise {\n if (this._storage.getItem(IS_COOKIE_ALLOWED_KEY)) {\n return Promise.resolve();\n }\n\n this._storage.setItem(IS_COOKIE_ALLOWED_KEY, true);\n\n // It could be possible that the flag is set to true but the browser has\n // already removed the permission to store third-party cookies. In that\n // case, we should try to redirect the user again. But we only want to\n // do it once within a fixed interval. This is to avoid getting into a\n // redirect loop if the shopper actually doesn't have a valid card\n // session.\n this._storage.setItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY, Date.now());\n\n const { origin } = parseUrl(this._options.url);\n const redirectUrl = `${origin}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(\n this._location.href,\n )}`;\n\n document.body.style.visibility = 'hidden';\n this._location.replace(redirectUrl);\n\n return new Promise(() => {});\n }\n\n private _retryAllowCookie(error: EmbeddedCheckoutError): Promise {\n const lastAttempt = Number(this._storage.getItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY));\n const canRetry =\n (!lastAttempt || Date.now() - lastAttempt > ALLOW_COOKIE_ATTEMPT_INTERVAL) &&\n error instanceof NotEmbeddableError &&\n error.subtype === NotEmbeddableErrorType.MissingContent;\n\n if (!canRetry) {\n return Promise.reject();\n }\n\n this._storage.removeItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY);\n this._storage.removeItem(IS_COOKIE_ALLOWED_KEY);\n\n return this._allowCookie();\n }\n}\n","import { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { appendWww, parseUrl } from '../common/url';\n\nimport { EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport { NotEmbeddableError, NotEmbeddableErrorType } from './errors';\n\nexport interface ExtendedHTMLIFrameElement extends HTMLIFrameElement {\n allowPaymentRequest?: boolean;\n}\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(src: string, containerId: string): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new NotEmbeddableError(\n 'Unable to embed the iframe because the container element could not be found.',\n NotEmbeddableErrorType.MissingContainer,\n );\n }\n\n const iframe: ExtendedHTMLIFrameElement = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n iframe.allowPaymentRequest = true;\n iframe.allow = 'payment';\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout).catch((error) => {\n container.removeChild(iframe);\n\n throw error;\n });\n }\n\n private _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n ): Promise {\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n reject(\n new NotEmbeddableError(\n 'Unable to embed the iframe because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (\n event.origin !== parseUrl(iframe.src).origin &&\n event.origin !== appendWww(parseUrl(iframe.src)).origin\n ) {\n return;\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameError)) {\n teardown();\n reject(\n new NotEmbeddableError(\n event.data.payload.message,\n NotEmbeddableErrorType.MissingContent,\n ),\n );\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameLoaded)) {\n iframe.style.display = '';\n\n const contentId = event.data.payload && event.data.payload.contentId;\n const iframes = iframeResizer(\n {\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: contentId ? 'taggedElement' : 'lowestElement',\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckout from './embedded-checkout';\nimport { EmbeddedCheckoutEventMap } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { EmbeddedContentEvent } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nconst STORAGE_PREFIX = 'BigCommerce.EmbeddedCheckout';\n\n/**\n * Embed the checkout form in an iframe.\n *\n * @remarks\n * Once the iframe is embedded, it will automatically resize according to the\n * size of the checkout form. It will also notify the parent window when certain\n * events have occurred. i.e.: when the form is loaded and ready to be used.\n *\n * ```js\n * embedCheckout({\n * url: 'https://checkout/url',\n * containerId: 'container-id',\n * });\n * ```\n *\n * @param options - Options for embedding the checkout form.\n * @returns A promise that resolves to an instance of `EmbeddedCheckout`.\n */\nexport default function embedCheckout(options: EmbeddedCheckoutOptions): Promise {\n const origin = parseUrl(options.url).origin;\n const embeddedCheckout = new EmbeddedCheckout(\n new ResizableIframeCreator(),\n new IframeEventListener(origin),\n new IframeEventPoster(origin),\n new LoadingIndicator({ styles: options.styles && options.styles.loadingIndicator }),\n createRequestSender(),\n new BrowserStorage(STORAGE_PREFIX),\n window.location,\n options,\n );\n\n return embeddedCheckout.attach();\n}\n","import { EmbeddedCheckoutFrameLoadedEvent } from '../embedded-checkout-events';\n\nexport default function handleFrameLoadedEvent(message: EmbeddedCheckoutFrameLoadedEvent): void {\n if (!message.payload || !message.payload.contentId) {\n return;\n }\n\n const body = document.getElementById(message.payload.contentId);\n\n if (!body || body.hasAttribute('data-iframe-height')) {\n return;\n }\n\n body.setAttribute('data-iframe-height', '');\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: unknown): error is CustomError {\n return typeof error === 'object' && error !== null && 'message' in error && 'type' in error;\n}\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { CustomError, isCustomError } from '../../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport EmbeddedCheckoutError from '../embedded-checkout-error';\nimport {\n EmbeddedCheckoutCompleteEvent,\n EmbeddedCheckoutErrorEvent,\n EmbeddedCheckoutEvent,\n EmbeddedCheckoutEventMap,\n EmbeddedCheckoutEventType,\n EmbeddedCheckoutFrameErrorEvent,\n EmbeddedCheckoutFrameLoadedEvent,\n EmbeddedCheckoutLoadedEvent,\n EmbeddedCheckoutSignedOutEvent,\n} from '../embedded-checkout-events';\nimport EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport { EmbeddedContentEventMap, EmbeddedContentEventType } from './embedded-content-events';\nimport EmbeddedContentOptions from './embedded-content-options';\n\n@bind\nexport default class IframeEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n /**\n * @internal\n */\n constructor(\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _untargetedMessagePoster: IframeEventPoster,\n private _messageHandlers: EventCallbacks = {},\n ) {\n this._messageListener.listen();\n }\n\n postComplete(): void {\n const message: EmbeddedCheckoutCompleteEvent = {\n type: EmbeddedCheckoutEventType.CheckoutComplete,\n };\n\n this._postMessage(message);\n }\n\n postError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutErrorEvent = {\n type: EmbeddedCheckoutEventType.CheckoutError,\n payload: this._transformError(payload),\n };\n\n this._postMessage(message);\n }\n\n postFrameError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutFrameErrorEvent = {\n type: EmbeddedCheckoutEventType.FrameError,\n payload: this._transformError(payload),\n };\n\n // Ideally, all messages should be targeted at a specific origin.\n // However, for `FrameError` message, we have to post it in an\n // untargeted fashion. This is because the error could be caused by a\n // missing cart. That makes it not possible to determine of site origin\n // of the parent window. Nevertheless, we still want to notify the\n // parent window about the error.\n this._postMessage(message, { untargeted: true });\n }\n\n postFrameLoaded(payload?: EmbeddedContentOptions): void {\n const message: EmbeddedCheckoutFrameLoadedEvent = {\n type: EmbeddedCheckoutEventType.FrameLoaded,\n payload,\n };\n\n this._postMessage(message);\n }\n\n postLoaded(): void {\n const message: EmbeddedCheckoutLoadedEvent = {\n type: EmbeddedCheckoutEventType.CheckoutLoaded,\n };\n\n this._postMessage(message);\n }\n\n postSignedOut(): void {\n const message: EmbeddedCheckoutSignedOutEvent = {\n type: EmbeddedCheckoutEventType.SignedOut,\n };\n\n this._postMessage(message);\n }\n\n receiveStyles(handler: (styles: EmbeddedCheckoutStyles) => void): void {\n this._messageListener.addListener(\n EmbeddedContentEventType.StyleConfigured,\n ({ payload }) => {\n handler(payload);\n },\n );\n }\n\n private _postMessage(message: EmbeddedCheckoutEvent, options?: { untargeted?: boolean }): void {\n this._notifyMessageHandlers(message);\n\n if (options && options.untargeted) {\n return this._untargetedMessagePoster.post(message);\n }\n\n this._messagePoster.post(message);\n }\n\n private _notifyMessageHandlers(message: EmbeddedCheckoutEvent): void {\n Object.keys(this._messageHandlers).forEach((key) => {\n if (message.type !== key) {\n return;\n }\n\n const handler = this._messageHandlers[key];\n\n if (handler) {\n (handler as (event: EmbeddedCheckoutEvent) => void).call(null, message);\n }\n });\n }\n\n private _transformError(error: Error | CustomError): EmbeddedCheckoutError {\n return {\n message: error.message,\n type: isCustomError(error) ? error.type : undefined,\n subtype: isCustomError(error) ? error.subtype : undefined,\n };\n }\n}\n\nexport type EventCallbacks = {\n [key in keyof TEventMap]?: (event: TEventMap[key]) => void;\n};\n","import { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\n\n@bind\nexport default class NoopEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n postComplete(): void {}\n\n postError(): void {}\n\n postFrameError(): void {}\n\n postFrameLoaded(): void {}\n\n postLoaded(): void {}\n\n postSignedOut(): void {}\n\n receiveStyles(): void {}\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../../common/iframe';\nimport { EmbeddedCheckoutEvent, EmbeddedCheckoutEventType } from '../embedded-checkout-events';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport EmbeddedCheckoutMessengerOptions from './embedded-checkout-messenger-options';\nimport { EmbeddedContentEventMap } from './embedded-content-events';\nimport handleFrameLoadedEvent from './handle-frame-loaded-event';\nimport IframeEmbeddedCheckoutMessenger from './iframe-embedded-checkout-messenger';\nimport NoopEmbeddedCheckoutMessenger from './noop-embedded-checkout-messenger';\n\n/**\n * Create an instance of `EmbeddedCheckoutMessenger`.\n *\n * @remarks\n * The object is responsible for posting messages to the parent window from the\n * iframe when certain events have occurred. For example, when the checkout\n * form is first loaded, you should notify the parent window about it.\n *\n * The iframe can only be embedded in domains that are allowed by the store.\n *\n * ```ts\n * const messenger = createEmbeddedCheckoutMessenger({\n * parentOrigin: 'https://some/website',\n * });\n *\n * messenger.postFrameLoaded();\n * ```\n *\n * @alpha\n * Please note that this feature is currently in an early stage of development.\n * Therefore the API is unstable and not ready for public consumption.\n *\n * @param options - Options for creating `EmbeddedCheckoutMessenger`\n * @returns - An instance of `EmbeddedCheckoutMessenger`\n */\nexport default function createEmbeddedCheckoutMessenger(\n options: EmbeddedCheckoutMessengerOptions,\n): EmbeddedCheckoutMessenger {\n setupContentWindowForIframeResizer();\n\n const parentWindow = options.parentWindow || window.parent;\n\n // Return a No-op messenger if it is not called inside an iframe\n if (window === parentWindow) {\n return new NoopEmbeddedCheckoutMessenger();\n }\n\n return new IframeEmbeddedCheckoutMessenger(\n new IframeEventListener(options.parentOrigin),\n new IframeEventPoster(options.parentOrigin, parentWindow),\n new IframeEventPoster('*', parentWindow),\n { [EmbeddedCheckoutEventType.FrameLoaded]: handleFrameLoadedEvent },\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"intl-messageformat\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"messageformat\");","import { FormatError, IntlMessageFormat } from 'intl-messageformat';\nimport { isObject, union } from 'lodash';\nimport MessageFormat from 'messageformat';\n\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { Logger } from '../common/log';\n\nimport LanguageConfig, {\n Locales,\n TransformedLanguageConfig,\n TransformedTranslations,\n Translations,\n} from './language-config';\n\nconst DEFAULT_LOCALE = 'en';\nconst KEY_PREFIX = 'optimized_checkout';\n\n/**\n * Responsible for getting language strings.\n *\n * This object can be used to retrieve language strings that are most\n * appropriate for a given locale.\n *\n * The language strings provided to the object should follow [ICU\n * MessageFormat](http://userguide.icu-project.org/formatparse/messages) syntax.\n */\n@bind\nexport default class LanguageService {\n private _locale: string;\n private _locales: Locales;\n private _translations: TransformedTranslations;\n private _formatters: { [key: string]: any };\n private _isCspNonceExperimentEnabled: boolean;\n\n /**\n * @internal\n */\n constructor(config: Partial, private _logger: Logger) {\n const { locale, locales, translations } = this._transformConfig(config);\n\n this._locale = locale;\n this._locales = locales;\n this._translations = translations;\n this._formatters = {};\n this._isCspNonceExperimentEnabled = config.isCspNonceExperimentEnabled ?? true;\n }\n\n /**\n * Remaps a set of language strings with a different set of keys.\n *\n * ```js\n * service.mapKeys({\n * 'new_key': 'existing_key',\n * });\n *\n * console.log(service.translate('new_key'));\n * ```\n *\n * @param maps - The set of language strings.\n */\n mapKeys(maps: { [key: string]: string }): void {\n Object.keys(maps).forEach((key) => {\n const translationKey = `${KEY_PREFIX}.${maps[key]}`;\n\n this._translations[`${KEY_PREFIX}.${key}`] = this._translations[translationKey];\n });\n }\n\n /**\n * Gets the preferred locale of the current customer.\n *\n * @returns The preferred locale code.\n */\n getLocale(): string {\n return this._hasTranslations() ? this._locale : DEFAULT_LOCALE;\n }\n\n /**\n * Gets a language string by a key.\n *\n * ```js\n * service.translate('language_key');\n * ```\n *\n * If the language string contains a placeholder, you can replace it by\n * providing a second argument.\n *\n * ```js\n * service.translate('language_key', { placeholder: 'Hello' });\n * ```\n *\n * @param key - The language key.\n * @param data - Data for replacing placeholders in the language string.\n * @returns The translated language string.\n */\n translate(key: string, data: TranslationData = {}): string {\n const prefixedKey = `${KEY_PREFIX}.${key}`;\n\n if (typeof this._translations[prefixedKey] !== 'string') {\n this._logger.warn(`Translation key \"${prefixedKey}\" is missing`);\n\n return prefixedKey;\n }\n\n if (this._isCspNonceExperimentEnabled) {\n if (!this._formatters[prefixedKey]) {\n this._formatters[prefixedKey] = new IntlMessageFormat(\n this._escapeSpecialCharacters(this._translations[prefixedKey] || ''),\n this._locales[prefixedKey],\n undefined,\n { ignoreTag: true },\n );\n }\n\n try {\n return this._formatters[prefixedKey].format(this._transformData(data));\n } catch (error) {\n if (this._isFormatError(error)) {\n return error.originalMessage ?? '';\n }\n\n throw error;\n }\n }\n\n if (!this._formatters[prefixedKey]) {\n const messageFormat = new MessageFormat(this._locales[prefixedKey]);\n\n this._formatters[prefixedKey] = messageFormat.compile(\n this._translations[prefixedKey] || '',\n );\n }\n\n return this._formatters[prefixedKey](this._transformData(data));\n }\n\n private _transformConfig(config: Partial = {}): TransformedLanguageConfig {\n const output: TransformedLanguageConfig = {\n defaultLocale: '',\n defaultTranslations: {},\n translations: {},\n locales: {},\n locale: config.locale || DEFAULT_LOCALE,\n };\n\n const locales = config.locales || {};\n const translations = this._flattenObject(config.translations || {});\n const defaultTranslations = this._flattenObject(config.defaultTranslations || {});\n const fallbackTranslations = this._flattenObject(config.fallbackTranslations || {});\n const translationKeys = union(\n Object.keys(fallbackTranslations),\n Object.keys(defaultTranslations),\n Object.keys(translations),\n );\n\n translationKeys.forEach((key) => {\n if (translations && translations[key]) {\n output.translations[key] = translations[key];\n output.locales[key] = locales[key] || output.locale;\n } else if (defaultTranslations[key]) {\n output.translations[key] = defaultTranslations[key];\n output.locales[key] = config.defaultLocale ?? DEFAULT_LOCALE;\n } else {\n output.translations[key] = fallbackTranslations[key];\n output.locales[key] = config.fallbackLocale ?? DEFAULT_LOCALE;\n }\n });\n\n return output;\n }\n\n private _flattenObject(\n object: Translations,\n result: TransformedTranslations = {},\n parentKey = '',\n ): TransformedTranslations {\n try {\n Object.keys(object).forEach((key) => {\n const value = object[key];\n const resultKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (isObject(value)) {\n return this._flattenObject(value, result, resultKey);\n }\n\n result[resultKey] = value;\n });\n } catch (err) {\n this._logger.warn(`Unable to parse object: ${err}`);\n }\n\n return result;\n }\n\n private _transformData(data: TranslationData): TranslationData {\n return Object.keys(data).reduce((result, key) => {\n const value = data[key];\n\n result[key] = value === null || value === undefined ? '' : value;\n\n return result;\n }, {} as TranslationData);\n }\n\n private _hasTranslations(): boolean {\n return (\n Object.keys(this._locales)\n .map((key) => this._locales[key])\n .filter((code) => code.split('-')[0] === this._locale.split('-')[0]).length > 0\n );\n }\n\n private _isFormatError(error: unknown): error is FormatError {\n return typeof error === 'object' && error !== null && 'originalMessage' in error;\n }\n\n private _escapeSpecialCharacters(message: string) {\n return message.replace(/(\\w+)='([^']*)'/g, \"$1=''$2''\");\n }\n}\n\nexport interface TranslationData {\n [key: string]: string | number;\n}\n","import { getDefaultLogger } from '../common/log';\n\nimport LanguageConfig from './language-config';\nimport LanguageService from './language-service';\n\n/**\n * Creates an instance of `LanguageService`.\n *\n * @remarks\n * ```js\n * const language = {{{langJson 'optimized_checkout'}}}; // `langJson` is a Handlebars helper provided by BigCommerce's Stencil template engine.\n * const service = createLanguageService(language);\n *\n * console.log(service.translate('address.city_label'));\n * ```\n *\n * @param config - A configuration object.\n * @returns An instance of `LanguageService`.\n */\nexport default function createLanguageService(\n config: Partial = {},\n): LanguageService {\n return new LanguageService(config, getDefaultLogger());\n}\n","import { CurrencyFormatter } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { bindDecorator as bind } from '@bigcommerce/checkout-sdk/utility';\n\nimport { StoreConfig } from '../config';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * @param config - The config object containing the currency configuration\n * @returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import {\n AnalyticsTrackerWindow,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\ninterface AnalyticsTrackerWindowGA extends AnalyticsTrackerWindow {\n ga(command: string, eventName: string, payload: AnalyticPayload): void;\n}\n\nfunction isAnalyticsTrackerWindowGA(\n window: Window | AnalyticsTrackerWindowGA,\n): window is AnalyticsTrackerWindowGA {\n return window && 'ga' in window && typeof window.ga === 'function';\n}\n\nexport function isGoogleAnalyticsAvailable(): boolean {\n return isAnalyticsTrackerWindow(window) && isAnalyticsTrackerWindowGA(window);\n}\n\nexport function sendGoogleAnalytics(type: string, payload: AnalyticPayload): void {\n if (isAnalyticsTrackerWindowGA(window)) {\n window.ga('send', type, {\n ...payload,\n nonInteraction: false,\n });\n }\n}\n\n/**\n * Max size of the payload for the Google Analytics module\n * if the limit will be succeeded, the GA throwing a silent error,\n * and only in debug mode you can see it\n */\nexport function isPayloadSizeLimitReached(obj: AnalyticPayload): boolean {\n const ANALYTICS_MAX_URI_LENGTH = 8096;\n\n return serializeAnalyticsEventPayload(obj).length >= ANALYTICS_MAX_URI_LENGTH;\n}\n\nfunction serializeAnalyticsEventPayload(obj: AnalyticPayload): string {\n return Object.keys(obj)\n .reduce((acc: string[], key) => {\n const type = typeof obj[key];\n\n if (type === 'string' || type === 'number') {\n return [...acc, `${key}=${obj[key]}`];\n }\n\n if (type === 'object' && obj[key] !== null) {\n return [...acc, serializeAnalyticsEventPayload(obj[key] as AnalyticPayload)];\n }\n\n return acc;\n }, [])\n .join('&');\n}\n\ninterface AnalyticPayload {\n [key: string]: unknown;\n}\n","import { keys } from 'lodash';\n\nimport {\n AnalyticsExtraItemsManager,\n AnalyticsTracker,\n ExtraItemsData,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { DigitalItem, LineItemMap, PhysicalItem } from '../cart';\nimport { Checkout, CheckoutService } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { ShopperCurrency, StoreProfile } from '../config';\nimport { Coupon } from '../coupon';\nimport { Order } from '../order';\nimport { ShippingOption } from '../shipping';\n\nimport {\n isGoogleAnalyticsAvailable,\n isPayloadSizeLimitReached,\n sendGoogleAnalytics,\n} from './analytics-tracker-ga';\nimport StepTracker from './step-tracker';\n\nexport interface StepTrackerConfig {\n checkoutSteps?: AnalyticStepType[];\n}\n\nexport type AnalyticStepType = 'customer' | 'shipping' | 'billing' | 'payment';\n\nexport enum AnalyticStepId {\n CUSTOMER = 1,\n SHIPPING,\n BILLING,\n PAYMENT,\n}\n\nconst ANALYTIC_STEPS: { [key: string]: AnalyticStepId } = {\n customer: AnalyticStepId.CUSTOMER,\n shipping: AnalyticStepId.SHIPPING,\n billing: AnalyticStepId.BILLING,\n payment: AnalyticStepId.PAYMENT,\n};\n\nexport default class AnalyticsStepTracker implements StepTracker {\n private _checkoutStarted = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private _viewedSteps: { [key in AnalyticStepId]?: boolean } = {};\n private _analyticStepOrder: AnalyticStepType[] = ['customer', 'shipping', 'billing', 'payment'];\n\n constructor(\n private checkoutService: CheckoutService,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n private analytics: AnalyticsTracker,\n { checkoutSteps }: StepTrackerConfig = {},\n ) {\n if (checkoutSteps !== undefined) {\n if (checkoutSteps.some((value) => !(value in ANALYTIC_STEPS))) {\n throw new InvalidArgumentError(\n `Invalid checkout steps provided. Valid values are: ${keys(ANALYTIC_STEPS).join(\n ', ',\n )}.`,\n );\n }\n\n this._analyticStepOrder = checkoutSteps;\n }\n }\n\n trackCheckoutStarted(): void {\n if (this._checkoutStarted) {\n return;\n }\n\n const checkout = this.getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const {\n coupons,\n grandTotal,\n shippingCostTotal,\n taxTotal,\n cart: { lineItems, discountAmount, id },\n } = checkout;\n\n const extraItemsData = this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n\n this.analytics.track(\n 'Checkout Started',\n this.getTrackingPayload({\n revenue: grandTotal,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n lineItems,\n extraItemsData,\n }),\n );\n\n this._checkoutStarted = true;\n }\n\n trackOrderComplete(): void {\n const order = this.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n taxTotal,\n discountAmount,\n coupons,\n lineItems,\n cartId,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n const extraItemsData = this.analyticsExtraItemsManager.readExtraItemsData(cartId);\n\n if (extraItemsData === null) {\n return;\n }\n\n const isMissingOrdersExperimentEnabled = this.checkoutService.getState().data.getConfig()\n ?.checkoutSettings.features['DATA-6891.missing_orders_within_GA'];\n\n const payload = this.getTrackingPayload({\n orderId,\n revenue: orderAmount,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n extraItemsData,\n lineItems,\n });\n\n if (\n isMissingOrdersExperimentEnabled &&\n isGoogleAnalyticsAvailable() &&\n isPayloadSizeLimitReached(payload)\n ) {\n sendGoogleAnalytics('transaction', {\n '&ti': payload.order_id,\n '&ta': payload.affiliation,\n '&tr': payload.revenue,\n '&ts': payload.shipping,\n '&tt': payload.tax,\n '&tcc': payload.coupon,\n '&cu': payload.currency,\n });\n payload.products.forEach((product) => {\n sendGoogleAnalytics('item', {\n '&ti': payload.order_id,\n '&in': product.name,\n '&ic': product.sku,\n '&iv': `${product.category}`,\n '&ip': product.price,\n '&iq': product.quantity,\n });\n });\n\n // TODO: decide how to send large orders to Segment without sending to GA again\n return this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n this.analytics.track('Order Completed', payload);\n\n this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n trackStepViewed(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepViewed(stepId)) {\n return;\n }\n\n this.trackViewed(stepId);\n this.backfill(stepId);\n }\n\n trackStepCompleted(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepCompleted(stepId)) {\n return;\n }\n\n this.backfill(stepId);\n this.trackCompleted(stepId);\n }\n\n private backfill(stepId: AnalyticStepId): void {\n for (const i of this._analyticStepOrder) {\n const id = this.getIdFromStep(i);\n\n if (!id) {\n break;\n }\n\n if (!this.hasStepViewed(id)) {\n this.trackViewed(id);\n }\n\n if (id === stepId) {\n break;\n }\n\n if (!this.hasStepCompleted(id)) {\n this.trackCompleted(id);\n }\n }\n }\n\n private trackCompleted(stepId: AnalyticStepId): void {\n const shippingMethod = this.getSelectedShippingOption();\n const { code: currency = '' } = this.getShopperCurrency() || {};\n const paymentMethod = this.getPaymentMethodName();\n\n const payload: {\n step: number;\n currency: string;\n shipping_method?: string;\n payment_method?: string;\n } = {\n step: stepId,\n currency,\n };\n\n if (shippingMethod) {\n payload.shipping_method = shippingMethod.description;\n }\n\n if (paymentMethod) {\n payload.payment_method = paymentMethod;\n }\n\n // due to an issue with the way the segment library works, we must send at least one of the two\n // options--otherwise it rejects the track call with no diagnostic messages. however, if we blindly\n // include both options, it sends a single comma for the value, which is undesireable. by only adding\n // one of the two (shippingMethod here being arbitrarily chosen), we always have at least one value, but\n // never send two empty values.\n if (!payload.shipping_method && !payload.payment_method) {\n payload.shipping_method = ' ';\n }\n\n this.analytics.track('Checkout Step Completed', payload);\n\n const shippingMethodId = shippingMethod ? shippingMethod.id : '';\n const completedStepId =\n stepId === AnalyticStepId.SHIPPING ? `${stepId}-${shippingMethodId}` : stepId;\n\n this._completedSteps[completedStepId] = true;\n }\n\n private getTrackingPayload({\n orderId,\n revenue,\n shipping,\n tax,\n discount,\n coupons,\n extraItemsData,\n lineItems,\n }: {\n orderId?: number;\n revenue: number;\n shipping: number;\n tax: number;\n discount: number;\n coupons: Coupon[];\n extraItemsData: ExtraItemsData;\n lineItems: LineItemMap;\n }) {\n const { code = '' } = this.getShopperCurrency() || {};\n const { storeName = '' } = this.getStoreProfile() || {};\n\n return {\n order_id: String(orderId),\n affiliation: storeName,\n revenue: this.toShopperCurrency(revenue),\n shipping: this.toShopperCurrency(shipping),\n tax: this.toShopperCurrency(tax),\n discount: this.toShopperCurrency(discount),\n coupon: (coupons || []).map((coupon) => coupon.code.toUpperCase()).join(','),\n currency: code,\n products: this.getProducts(extraItemsData, lineItems),\n };\n }\n\n private hasStepCompleted(stepId: AnalyticStepId): boolean {\n const shippingOption = this.getSelectedShippingOption();\n const shippingMethodId = shippingOption ? shippingOption.id : '';\n\n return (\n Object.prototype.hasOwnProperty.call(this._completedSteps, stepId) ||\n (stepId === AnalyticStepId.SHIPPING &&\n Object.prototype.hasOwnProperty.call(\n this._completedSteps,\n `${stepId}-${shippingMethodId}`,\n ))\n );\n }\n\n private hasStepViewed(stepId: AnalyticStepId): boolean {\n return !!this._viewedSteps[stepId];\n }\n\n private getIdFromStep(step: string): AnalyticStepId | null {\n const name = step.split('.');\n\n return ANALYTIC_STEPS[name[0]] || null;\n }\n\n private trackViewed(stepId: AnalyticStepId): void {\n const currency = this.getShopperCurrency();\n\n this.analytics.track('Checkout Step Viewed', {\n step: stepId,\n currency: currency ? currency.code : '',\n });\n\n this._viewedSteps[stepId] = true;\n }\n\n private getOrder(): Order | undefined {\n const {\n data: { getOrder },\n } = this.checkoutService.getState();\n\n return getOrder();\n }\n\n private getCheckout(): Checkout | undefined {\n const {\n data: { getCheckout },\n } = this.checkoutService.getState();\n\n return getCheckout();\n }\n\n private getShopperCurrency(): ShopperCurrency | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.shopperCurrency;\n }\n\n private getStoreProfile(): StoreProfile | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.storeProfile;\n }\n\n private toShopperCurrency(amount: number): number {\n const { exchangeRate = 1 } = this.getShopperCurrency() || {};\n\n return Math.round(amount * exchangeRate * 100) / 100;\n }\n\n private getSelectedShippingOption(): ShippingOption | null {\n const { data } = this.checkoutService.getState();\n const shippingOption = data.getSelectedShippingOption();\n\n return shippingOption && shippingOption.id && shippingOption.description\n ? shippingOption\n : null;\n }\n\n private getPaymentMethodName(): string {\n const { data } = this.checkoutService.getState();\n const paymentMethod = data.getSelectedPaymentMethod();\n\n return paymentMethod && paymentMethod.config ? paymentMethod.config.displayName || '' : '';\n }\n\n private getProducts(itemsData: ExtraItemsData, lineItems: LineItemMap): AnalyticsProduct[] {\n const customItems: AnalyticsProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n price: item.listPrice,\n quantity: item.quantity,\n name: item.name,\n }));\n\n const giftCertificateItems: AnalyticsProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n price: this.toShopperCurrency(item.amount),\n name: item.name,\n quantity: 1,\n };\n });\n\n const transformItem = (item: PhysicalItem | DigitalItem): AnalyticsProduct => {\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n const variant =\n Array.isArray(itemAttributes) && itemAttributes.length\n ? itemAttributes.join(', ')\n : 'single-product-option';\n\n const brand = itemsData[item.productId] && itemsData[item.productId].brand;\n\n return {\n product_id: String(item.productId),\n sku: item.sku,\n price: item.salePrice,\n image_url: item.imageUrl,\n name: item.name,\n quantity: item.quantity,\n category: itemsData[item.productId] ? itemsData[item.productId].category : '',\n variant,\n ...(brand && { brand }),\n };\n };\n\n const physicalAndDigitalItems: AnalyticsProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map(transformItem);\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems];\n }\n}\n\nexport interface AnalyticsProduct {\n product_id: string | number;\n price: number;\n quantity: number;\n name: string;\n sku?: string;\n image_url?: string;\n category?: string;\n variant?: string;\n brand?: string;\n}\n","import StepTracker from './step-tracker';\n\nexport default class NoopStepTracker implements StepTracker {\n trackCheckoutStarted(): void {}\n\n trackOrderComplete(): void {}\n\n trackStepViewed(): void {}\n\n trackStepCompleted(): void {}\n}\n","import localStorageFallback from 'local-storage-fallback';\n\nimport {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { CheckoutService } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport AnalyticsStepTracker, { StepTrackerConfig } from './analytics-step-tracker';\nimport NoopStepTracker from './noop-step-tracker';\nimport StepTracker from './step-tracker';\n\n/**\n * Creates an instance of `StepTracker`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const stepTracker = createStepTracker(checkoutService);\n *\n * stepTracker.trackCheckoutStarted();\n * ```\n *\n * @param CheckoutService - An instance of CheckoutService\n * @param StepTrackerConfig - A step tracker config object\n * @returns an instance of `StepTracker`.\n */\nexport default function createStepTracker(\n checkoutService: CheckoutService,\n stepTrackerConfig?: StepTrackerConfig,\n): StepTracker {\n const { data } = checkoutService.getState();\n const config = data.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { isAnalyticsEnabled } = config.checkoutSettings;\n\n if (isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n return new AnalyticsStepTracker(\n checkoutService,\n new AnalyticsExtraItemsManager(localStorageFallback),\n window.analytics,\n stepTrackerConfig,\n );\n }\n\n return new NoopStepTracker();\n}\n","import { BraintreeFastlaneWindow } from '../types';\n\nexport default function isBraintreeFastlaneWindow(\n window: Window,\n): window is BraintreeFastlaneWindow {\n return Boolean(window.hasOwnProperty('braintreeFastlane'));\n}\n","import {\n BraintreeFastlane,\n BraintreeFastlaneApmSelectedEventOptions,\n BraintreeFastlaneEmailEnteredEventOptions,\n BraintreeFastlaneEventCommonOptions,\n BraintreeFastlaneOrderPlacedEventOptions,\n isBraintreeFastlaneWindow,\n} from '@bigcommerce/checkout-sdk/braintree-utils';\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutService } from '../../checkout';\n\nimport BraintreeAnalyticTrackerService from './braintree-analytic-tracker-service';\n\nexport default class BraintreeAnalyticTracker implements BraintreeAnalyticTrackerService {\n private _selectedPaymentMethodId = '';\n\n constructor(private checkoutService: CheckoutService) {}\n\n customerPaymentMethodExecuted() {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackEmailSubmitted();\n }\n }\n\n paymentComplete() {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackOrderPlaced(this._selectedPaymentMethodId);\n }\n }\n\n selectedPaymentMethod(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, false);\n }\n }\n\n walletButtonClick(methodId: string) {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, true);\n }\n }\n\n private _shouldTrackFastlaneEvent() {\n const state = this.checkoutService.getState();\n const paymentMethod =\n state.data.getPaymentMethod('braintree') ||\n state.data.getPaymentMethod('braintreeacceleratedcheckout');\n const isAnalyticEnabled = paymentMethod?.initializationData.isBraintreeAnalyticsV2Enabled;\n\n const isAvailableAnalyticEventsMethods =\n isBraintreeFastlaneWindow(window) && window.braintreeFastlane.events;\n\n return isAnalyticEnabled && isAvailableAnalyticEventsMethods;\n }\n\n private _getBraintreeEventsOrThrow(): BraintreeFastlane['events'] {\n if (isBraintreeFastlaneWindow(window)) {\n return window.braintreeFastlane.events;\n }\n\n throw new PaymentMethodClientUnavailableError();\n }\n\n /**\n *\n * Braintree Events tracking methods\n *\n */\n private _trackEmailSubmitted(): void {\n const { emailSubmitted } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getEmailSubmittedEventOptions();\n\n emailSubmitted(eventOptions);\n }\n\n private _trackApmSelected(methodId: string, isWalletButton: boolean): void {\n const { apmSelected } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getApmSelectedEventOptions(methodId, isWalletButton);\n\n apmSelected(eventOptions);\n }\n\n private _trackOrderPlaced(methodId: string): void {\n const { orderPlaced } = this._getBraintreeEventsOrThrow();\n const eventOptions = this._getOrderPlacedEventOptions(methodId);\n\n orderPlaced(eventOptions);\n }\n\n /**\n *\n * Event options methods\n *\n */\n private _getEventCommonOptions(): BraintreeFastlaneEventCommonOptions {\n const state = this.checkoutService.getState();\n const cart = state.data.getCart();\n const storeProfile = state.data.getConfig()?.storeProfile;\n const isGuestCustomer = state.data.getCustomer()?.isGuest;\n\n const paymentMethod = state.data.getPaymentMethod('braintreeacceleratedcheckout');\n const isTestTreatmentGroup =\n !state.errors.getLoadPaymentMethodError('braintreeacceleratedcheckout') &&\n paymentMethod?.initializationData.shouldRunAcceleratedCheckout;\n\n const experiments = [\n {\n treatment_group: isTestTreatmentGroup ? 'test' : 'control',\n },\n ];\n\n return {\n context_type: 'cs_id',\n context_id: cart?.id || '',\n page_type: 'checkout_page',\n page_name: window.document.title,\n partner_name: 'bigc',\n user_type: isGuestCustomer ? 'store_guest' : 'store_member',\n store_id: storeProfile?.storeId || '',\n merchant_name: storeProfile?.storeName || '',\n experiment: JSON.stringify(experiments),\n };\n }\n\n private _getEmailSubmittedEventOptions(): BraintreeFastlaneEmailEnteredEventOptions {\n const state = this.checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n user_email_saved: false,\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n };\n }\n\n private _getApmSelectedEventOptions(\n methodId: string,\n isWalletButton: boolean,\n ): BraintreeFastlaneApmSelectedEventOptions {\n const state = this.checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n apm_selected: methodId,\n apm_location: isWalletButton ? 'pre-email section' : 'payment section',\n };\n }\n\n private _getOrderPlacedEventOptions(\n methodId: string,\n ): BraintreeFastlaneOrderPlacedEventOptions {\n const state = this.checkoutService.getState().data;\n const cart = state.getCart();\n\n return {\n ...this._getEventCommonOptions(),\n selected_payment_method: methodId,\n currency_code: cart?.currency.code || '',\n };\n }\n}\n","import { CheckoutService } from '../../checkout';\n\nimport BraintreeAnalyticTracker from './braintree-analytic-tracker';\nimport BraintreeAnalyticTrackerService from './braintree-analytic-tracker-service';\n\n/**\n * Creates an instance of `BraintreeAnalyticTrackerService`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const braintreeAnalyticTracker = createBraintreeAnalyticTracker(checkoutService);\n *\n * braintreeAnalyticTracker.customerPaymentMethodExecuted();\n * braintreeAnalyticTracker.paymentComplete();\n * braintreeAnalyticTracker.selectedPaymentMethod('applepay');\n * braintreeAnalyticTracker.walletButtonClick('paypal');\n * ```\n *\n * @returns an instance of `BraintreeAnalyticTrackerService`.\n */\nexport default function createBraintreeAnalyticTracker(\n checkoutService: CheckoutService,\n): BraintreeAnalyticTrackerService {\n return new BraintreeAnalyticTracker(checkoutService);\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport {\n PayPalCommerceHostWindow,\n PayPalFastlaneApmSelectedEventOptions,\n PayPalFastlaneEmailEnteredEventOptions,\n PayPalFastlaneEventCommonOptions,\n PayPalFastlaneEvents,\n PayPalFastlaneOrderPlacedEventOptions,\n} from '@bigcommerce/checkout-sdk/paypal-commerce-utils';\n\nimport { CheckoutService } from '../../checkout';\n\nimport PayPalCommerceAnalyticTrackerService from './paypal-commerce-analytic-tracker-service';\n\nexport default class PayPalCommerceAnalyticTracker implements PayPalCommerceAnalyticTrackerService {\n private _selectedPaymentMethodId = '';\n\n constructor(private _checkoutService: CheckoutService) {}\n\n customerPaymentMethodExecuted(): void {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackEmailSubmitted();\n }\n }\n\n paymentComplete(): void {\n if (this._shouldTrackFastlaneEvent()) {\n this._trackOrderPlaced(this._selectedPaymentMethodId);\n }\n }\n\n selectedPaymentMethod(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, false);\n }\n }\n\n walletButtonClick(methodId: string): void {\n if (this._shouldTrackFastlaneEvent() && methodId) {\n this._selectedPaymentMethodId = methodId;\n\n this._trackApmSelected(methodId, true);\n }\n }\n\n private _shouldTrackFastlaneEvent(): boolean {\n const state = this._checkoutService.getState();\n const paymentMethod = state.data.getPaymentMethod('paypalcommerce');\n const initializationData = paymentMethod?.initializationData || {};\n const isAnalyticEnabled = initializationData.isPayPalCommerceAnalyticsV2Enabled;\n\n const paypalHostWindow = window as PayPalCommerceHostWindow;\n const isAvailableAnalyticEventsMethods = paypalHostWindow.paypalFastlane\n ? !!paypalHostWindow.paypalFastlane.events\n : false;\n\n return isAnalyticEnabled && isAvailableAnalyticEventsMethods;\n }\n\n private _getPayPalEventsOrThrow(): PayPalFastlaneEvents {\n const paypalHostWindow = window as PayPalCommerceHostWindow;\n\n if (paypalHostWindow.paypalFastlane && paypalHostWindow.paypalFastlane.events) {\n return paypalHostWindow.paypalFastlane.events;\n }\n\n throw new PaymentMethodClientUnavailableError();\n }\n\n /**\n *\n * Analytic Event track methods\n *\n */\n private _trackEmailSubmitted(): void {\n const { emailSubmitted } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getEmailSubmittedEventOptions();\n\n emailSubmitted(eventOptions);\n }\n\n private _trackApmSelected(methodId: string, isWalletButton: boolean): void {\n const { apmSelected } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getApmSelectedEventOptions(methodId, isWalletButton);\n\n apmSelected(eventOptions);\n }\n\n private _trackOrderPlaced(methodId: string): void {\n const { orderPlaced } = this._getPayPalEventsOrThrow();\n const eventOptions = this._getOrderPlacedEventOptions(methodId);\n\n orderPlaced(eventOptions);\n }\n\n /**\n *\n * Event options methods\n *\n */\n private _getEventCommonOptions(): PayPalFastlaneEventCommonOptions {\n const state = this._checkoutService.getState();\n const cart = state.data.getCart();\n const storeProfile = state.data.getConfig()?.storeProfile;\n const isGuestCustomer = state.data.getCustomer()?.isGuest;\n const methodId = 'paypalcommerceacceleratedcheckout';\n\n const paymentMethod = state.data.getPaymentMethod(methodId);\n const isTestTreatmentGroup =\n !state.errors.getLoadPaymentMethodError(methodId) &&\n paymentMethod?.initializationData.shouldRunAcceleratedCheckout;\n\n const experiments = [\n {\n treatment_group: isTestTreatmentGroup ? 'test' : 'control',\n },\n ];\n\n return {\n context_type: 'cs_id',\n context_id: cart?.id.replace(/-/g, '') || '',\n page_type: 'checkout_page',\n page_name: window.document.title,\n partner_name: 'bigc',\n user_type: isGuestCustomer ? 'store_guest' : 'store_member',\n store_id: storeProfile?.storeId || '',\n merchant_name: storeProfile?.storeName || '',\n experiment: JSON.stringify(experiments),\n };\n }\n\n private _getEmailSubmittedEventOptions(): PayPalFastlaneEmailEnteredEventOptions {\n const state = this._checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n user_email_saved: false,\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n };\n }\n\n private _getApmSelectedEventOptions(\n methodId: string,\n isWalletButton: boolean,\n ): PayPalFastlaneApmSelectedEventOptions {\n const state = this._checkoutService.getState().data;\n const paymentMethods = state.getPaymentMethods() || [];\n const apmList = paymentMethods.map(({ id }) => id);\n\n return {\n ...this._getEventCommonOptions(),\n apm_shown: apmList.length > 1 ? '1' : '0',\n apm_list: apmList.join(','),\n apm_selected: methodId,\n apm_location: isWalletButton ? 'pre-email section' : 'payment section',\n };\n }\n\n private _getOrderPlacedEventOptions(methodId: string): PayPalFastlaneOrderPlacedEventOptions {\n const state = this._checkoutService.getState().data;\n const cart = state.getCart();\n\n return {\n ...this._getEventCommonOptions(),\n selected_payment_method: methodId,\n currency_code: cart?.currency.code || '',\n };\n }\n}\n","import { CheckoutService } from '../../checkout';\n\nimport PayPalCommerceAnalyticTracker from './paypal-commerce-analytic-tracker';\nimport PayPalCommerceAnalyticTrackerService from './paypal-commerce-analytic-tracker-service';\n\n/**\n * Creates an instance of `PayPalCommerceAnalyticTrackerService`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const paypalCommerceAnalyticTracker = createPayPalCommerceAnalyticTracker(checkoutService);\n *\n * paypalCommerceAnalyticTracker.customerPaymentMethodExecuted();\n * paypalCommerceAnalyticTracker.paymentComplete();\n * paypalCommerceAnalyticTracker.selectedPaymentMethod('applepay');\n * paypalCommerceAnalyticTracker.walletButtonClick('paypal');\n * ```\n *\n * @returns an instance of `PayPalCommerceAnalyticTrackerService`.\n */\nexport default function createPayPalCommerceAnalyticTracker(\n checkoutService: CheckoutService,\n): PayPalCommerceAnalyticTrackerService {\n return new PayPalCommerceAnalyticTracker(checkoutService);\n}\n","import { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport HostedForm from './hosted-form';\nimport HostedFormFactory from './hosted-form-factory';\nimport LegacyHostedFormOptions from './hosted-form-options';\nimport {\n StoredCardHostedFormData,\n StoredCardHostedFormInstrumentFields,\n} from './stored-card-hosted-form-type';\n\nexport default class StoredCardHostedFormService {\n protected _hostedForm?: HostedForm;\n constructor(protected _host: string, protected _hostedFormFactory: HostedFormFactory) {}\n\n async submitStoredCard(\n fields: StoredCardHostedFormInstrumentFields,\n data: StoredCardHostedFormData,\n ): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate().then(() => form.submitStoredCard({ fields, data }));\n }\n\n initialize(options: LegacyHostedFormOptions): Promise {\n const form = this._hostedFormFactory.create(this._host, options);\n\n return form.attach().then(() => {\n this._hostedForm = form;\n });\n }\n\n deinitialize() {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { createCheckoutStore } from '../checkout';\n\nimport HostedFormFactory from './hosted-form-factory';\nimport StoredCardHostedFormService from './stored-card-hosted-form-service';\n\n/**\n * Creates an instance of `StoredCardHostedFormService`.\n *\n *\n * @param host - Host url string parameter.\n * @returns An instance of `StoredCardHostedFormService`.\n */\nexport default function createStoredCardHostedFormService(host: string) {\n const store = createCheckoutStore();\n\n return new StoredCardHostedFormService(host, new HostedFormFactory(store));\n}\n","export enum AnalyticStepType {\n CUSTOMER = 'customer',\n SHIPPING = 'shipping',\n BILLING = 'billing',\n PAYMENT = 'payment',\n}\n\nexport const AnalyticStepOrder: AnalyticStepType[] = [\n AnalyticStepType.CUSTOMER,\n AnalyticStepType.SHIPPING,\n AnalyticStepType.BILLING,\n AnalyticStepType.PAYMENT,\n];\n","import { flatten } from 'lodash';\n\nimport { LineItem, LineItemMap } from '../cart';\nimport { CheckoutSelectors, CheckoutStoreSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { AnalyticStepOrder, AnalyticStepType } from './analytics-steps';\nimport BodlService from './bodl-service';\nimport {\n BodlEventsCheckout,\n BodlEventsPayload,\n BODLProduct,\n CommonCheckoutData,\n} from './bodl-window';\n\nexport default class BodlEmitterService implements BodlService {\n private _checkoutStarted = false;\n private _emailEntryBegan = false;\n private _shippingOptionsShown = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private state?: CheckoutStoreSelector;\n\n constructor(\n private subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n private bodlEvents: BodlEventsCheckout,\n ) {\n this.subscribe((state) => {\n this.setState(state.data);\n\n const config = this.state?.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n });\n }\n\n setState(state: CheckoutStoreSelector) {\n this.state = state;\n }\n\n checkoutBegin(): void {\n const data = this._getCommonCheckoutData();\n\n if (this._checkoutStarted || !data) {\n return;\n }\n\n this.bodlEvents.emitCheckoutBeginEvent(data);\n\n this._checkoutStarted = true;\n }\n\n orderPurchased(): void {\n const order = this.state?.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n currency,\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n lineItems,\n cartId,\n coupons,\n channelId,\n taxTotal,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n this.bodlEvents.emitOrderPurchasedEvent({\n event_id: cartId,\n currency: currency.code,\n order_id: orderId,\n tax: taxTotal,\n channel_id: channelId,\n cart_value: orderAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n shipping_cost: shippingCostTotal,\n line_items: this._getProducts(lineItems, currency.code),\n });\n }\n\n stepCompleted(currentStep?: AnalyticStepType): void {\n if (!currentStep) {\n return;\n }\n\n AnalyticStepOrder.some((step: AnalyticStepType) => {\n if (!this._hasStepCompleted(step)) {\n this._trackCompletedStep(step);\n }\n\n return step === currentStep;\n });\n }\n\n customerEmailEntry(email?: string) {\n if (this._emailEntryBegan || !email?.length) {\n return;\n }\n\n this._emailEntryBegan = true;\n this.bodlEvents.emit('bodl_checkout_email_entry_began');\n }\n\n customerSuggestionInit(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_initialization', payload);\n }\n\n customerSuggestionExecute() {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_execute');\n }\n\n customerPaymentMethodExecuted(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_payment_method_executed', payload);\n }\n\n showShippingMethods() {\n if (this._shippingOptionsShown) {\n return;\n }\n\n this._shippingOptionsShown = true;\n this.bodlEvents.emit('bodl_checkout_show_shipping_options');\n }\n\n selectedPaymentMethod(paymentOption?: string) {\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !paymentOption) {\n return;\n }\n\n this.bodlEvents.emitPaymentDetailsProvidedEvent({\n ...commonData,\n payment_type: paymentOption,\n });\n }\n\n clickPayButton(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_click_pay_button', payload);\n }\n\n paymentRejected() {\n this.bodlEvents.emit('bodl_checkout_payment_rejected');\n }\n\n paymentComplete() {\n this.bodlEvents.emit('bodl_checkout_payment_complete');\n }\n\n exitCheckout() {\n this.bodlEvents.emit('bodl_checkout_exit');\n }\n\n private _trackCompletedStep(step: AnalyticStepType) {\n this._completedSteps[step] = true;\n\n const bodlEventsMap: { [key in AnalyticStepType]?: () => void } = {\n [AnalyticStepType.SHIPPING]: this._trackShippingStepCompleted.bind(this),\n };\n const emit = bodlEventsMap[step];\n\n if (emit) {\n emit();\n } else {\n this.bodlEvents.emit('bodl_checkout_step_completed', { step });\n }\n }\n\n private _trackShippingStepCompleted(): void {\n const shippingMethod = this.state?.getSelectedShippingOption()?.description;\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !shippingMethod) {\n return;\n }\n\n this.bodlEvents.emitShippingDetailsProvidedEvent({\n ...commonData,\n shipping_method: shippingMethod,\n });\n }\n\n private _getCommonCheckoutData(): CommonCheckoutData | null {\n const checkout = this.state?.getCheckout();\n\n if (!checkout) {\n return null;\n }\n\n const {\n cart: { cartAmount, currency, lineItems, id, coupons },\n channelId,\n } = checkout;\n\n return {\n event_id: id,\n currency: currency.code,\n cart_value: cartAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n line_items: this._getProducts(lineItems, currency.code),\n channel_id: channelId,\n };\n }\n\n private _getProducts(lineItems: LineItemMap, currencyCode: string): BODLProduct[] {\n const customItems: BODLProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n base_price: item.listPrice,\n sale_price: item.listPrice,\n purchase_price: item.listPrice,\n quantity: item.quantity,\n product_name: item.name,\n currency: currencyCode,\n }));\n\n const giftCertificateItems: BODLProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n gift_certificate_id: item.id,\n base_price: item.amount,\n sale_price: item.amount,\n purchase_price: item.amount,\n product_name: item.name,\n gift_certificate_name: item.name,\n gift_certificate_theme: item.theme,\n quantity: 1,\n currency: currencyCode,\n };\n });\n\n const physicalAndDigitalItems: BODLProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n const getCategoryNames = (lineItem: LineItem): string[] => {\n if (Array.isArray(lineItem.categoryNames)) {\n return lineItem.categoryNames;\n } else if (Array.isArray(lineItem.categories)) {\n return flatten(lineItem.categories).map(({ name }) => name);\n }\n\n return [];\n };\n\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n quantity: item.quantity,\n product_name: item.name,\n base_price: item.listPrice,\n sale_price: item.salePrice,\n purchase_price: item.salePrice > 0 ? item.salePrice : item.listPrice,\n sku: item.sku,\n variant_id: item.variantId,\n discount: item.discountAmount,\n coupon_amount: item.couponAmount,\n brand_name: item.brand,\n currency: currencyCode,\n category_names: getCategoryNames(item),\n retail_price: item.retailPrice,\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems].map(\n (item) => ({\n ...item,\n product_id: String(item.product_id),\n }),\n );\n }\n\n private _hasStepCompleted(step: AnalyticStepType): boolean {\n return this._completedSteps[step];\n }\n}\n","import BodlService from './bodl-service';\n\nexport default class NoopBodlService implements BodlService {\n checkoutBegin(): void {}\n\n orderPurchased(): void {}\n\n stepCompleted(): void {}\n\n customerEmailEntry(): void {}\n\n customerSuggestionInit(): void {}\n\n customerSuggestionExecute(): void {}\n\n customerPaymentMethodExecuted(): void {}\n\n showShippingMethods(): void {}\n\n selectedPaymentMethod(): void {}\n\n clickPayButton(): void {}\n\n paymentRejected(): void {}\n\n paymentComplete(): void {}\n\n exitCheckout(): void {}\n}\n","import { CheckoutSelectors } from '../checkout';\n\nimport BodlEmitterService from './bodl-emitter-service';\nimport BodlService from './bodl-service';\nimport { isBodlEnabled } from './is-bodl-enabled';\nimport NoopBodlService from './noop-bodl-service';\n\n/**\n * Creates an instance of `BodlService`.\n *\n * @remarks\n *\n * ```js\n * const bodlService = BodlService();\n * bodlService.checkoutBegin();\n *\n * ```\n *\n * @param subscribe - The callback function, what get a subscriber as a property, that subscribes to state changes.\n * @returns an instance of `BodlService`.\n */\nexport default function createBodlService(\n subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n): BodlService {\n if (isBodlEnabled(window)) {\n return new BodlEmitterService(subscribe, window.bodlEvents.checkout);\n }\n\n return new NoopBodlService();\n}\n","import BodlEventsWindow from './bodl-window';\n\nexport function isBodlEnabled(window: Window): window is BodlEventsWindow {\n return 'bodlEvents' in window;\n}\n"],"names":["module","exports","require","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","throwErrorAction","type","error","meta","action","concat","of","throwError","createErrorAction","payload","message","object","name","setPrototypeOf","__proto__","Error","captureStackTrace","stack","MissingDataErrorType","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingPaymentProviderCustomer","MissingShippingAddress","getErrorMessage","BillingAddressActionType","_requestSender","_subscriptionActionCreator","continueAsGuest","credentials","options","store","state","getState","checkout","getCheckout","isBillingFixExperimentEnabled","config","getConfig","storeConfig","checkoutSettings","features","customer","getCustomer","isGuest","billingAddressRequestBody","billingAddress","getBillingAddress","existingBillingAddressRequestBody","hasBillingAddress","isEmpty","merge","createAction","ContinueAsGuestRequested","defer","this","_createOrUpdateBillingAddress","id","body","ContinueAsGuestSucceeded","pipe","catchError","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","Observable","create","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","empty","updateSubscriptions","checkoutId","createAddress","ContentType","SDK_VERSION_HEADERS","DEFAULT_PARAMS","include","join","timeout","url","headers","Accept","JsonV1","post","params","put","ProjectionActionType","ErrorActionType","createDataStoreProjection","stateTransformer","projection","createDataStore","Synchronize","subscribe","dispatch","initial","clearError","ClearError","getEnvironment","process","env","NODE_ENV","e","_console","log","_logToConsole","messages","info","warn","debug","isEnabled","logger","console","getDefaultLogger","ConfigActionType","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","param","lastArg","args","length","useCache","fn","instanceMethods","set","memoize","from","shareReplay","isEqual","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","DEFAULT_RESPONSE","status","errors","title","INTERNAL_USE_ONLY","CouponActionType","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","CheckoutIncludes","joinIncludes","includes","uniq","couponCode","AvailableShippingOptions","delete","GiftCertificateActionType","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","giftCertificateCode","isResolvableModule","_factories","_instances","_defaultToken","defaultToken","_useFallback","useFallback","_tokenResolver","tokenResolver","token","cacheToken","_getInstance","register","factory","_hasFactory","_hasInstance","resolvedToken","keys","_registry","_resolveToken","bind","resolveId","_encodeToken","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","default","entries","push","matchedResults","sort","b","filter","matched","find","getShippableItemsCount","cart","lineItems","physicalItems","item","addedByPromotion","reduce","total","quantity","guard","errorFactory","NotInitializedErrorType","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","amazonPayV2Regions","de","jp","uk","us","amazonPayV2ScriptLoader","initialize","paymentMethod","load","amazonPayV2SDK","buttonParentContainer","createAmazonPayButtonParentContainer","deinitialize","amazonPayV2Button","remove","Promise","resolve","bindButton","buttonId","sessionId","changeAction","getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","containerId","renderButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","prepareRequestConfig","getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","checkoutState","decoupleCheckoutInitiation","methodId","placement","isButtonMicroTextDisabled","container","document","querySelector","parentContainerId","appendChild","getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","getAmazonPayV2ButtonOptions","updateBuyNowFlowFlag","isBuyNowFlow","Boolean","isPh4Enabled","storeCountryCode","isPh4UsOnly","publicKeyId","signedPayload","isEnvironmentSpecific","uid","Math","random","toString","substr","parentContainer","createElement","Gold","getCheckoutState","getCart","getStoreConfigOrThrow","getPaymentMethodOrThrow","merchantId","testMode","initializationData","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","storeProfile","shopPath","amount","outstandingBalance","currencyCode","currency","buttonOptions","tmpConfig","createCheckoutSession","test","getOrThrow","checkoutSelectors","paymentMethods","scriptLoader","windowWithAmazonPay","window","region","amazonPayV2Region","loadScript","amazon","createAmazonPayV2PaymentProcessor","getScriptLoader","toResolvableModule","resolveIds","assign","paymentIntegrationService","amazonPayV2PaymentProcessor","amazonpay","loadPaymentMethod","Checkout","signIn","signOut","payment","getPaymentId","remoteCheckoutSignOut","providerId","executePaymentMethodCheckout","continueWithCheckoutCallback","TotalPriceStatusType","BraintreeFastlaneAuthenticationState","BraintreeErrorType","BraintreeErrorCode","NonInstantLocalPaymentMethods","isBraintreeError","braintreeScriptLoader","clientToken","setClientToken","teardownModule","dataCollector","getClient","client","getClientTokenOrThrow","loadClient","clientCreator","authorization","getDataCollectorOrThrow","emptyDataCollector","deviceData","teardown","loadDataCollector","dataCollectorConfig","kount","KountNotEnabled","getBraintreeGooglePayment","googlePayment","all","loadGooglePayment","braintreeGooglePayment","getBraintreeThreeDS","threeDS","load3DS","threeDSecure","version","getBraintreeLocalPayment","merchantAccountId","braintreeLocalPayment","loadLocalPayment","reject","getUsBankAccount","usBankAccount","loadUsBankAccount","getBraintreeVisaCheckout","visaCheckout","loadVisaCheckout","getVisaCheckoutSdk","visaCheckoutSDK","loadVisaCheckoutSdk","getVenmoCheckoutOrThrow","braintreeVenmo","loadVenmoCheckout","venmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","braintreeVenmoCheckout","isBrowserSupported","BraintreeEnv","BraintreeModuleName","BraintreeFormFieldType","BRAINTREE_SDK_SCRIPTS_INTEGRITY","Client","PaypalCheckout","Paypal","LocalPayment","DataCollector","UsBankAccount","GooglePayment","ThreeDSecure","VisaCheckout","Venmo","HostedFields","Fastlane","braintreeHostWindow","braintreeSdkVersion","loadBraintreeModuleOrThrow","loadFastlane","loadPaypalCheckout","loadPaypal","loadHostedFields","V","hash","async","attributes","integrity","crossorigin","braintreeModuleName","fileName","getBraintreeModule","scriptPath","getIntegrityValuesByModuleName","braintree","moduleName","ApplePayGatewayType","assertApplePayWindow","isApplePayWindow","request","ApplePaySession","DefaultLabels","_paymentIntegrationService","_sessionFactory","_braintreeSdk","_onAuthorizeCallback","noop","_onError","_onClick","_subTotalLabel","Subtotal","_shippingLabel","Shipping","_hasApplePaySession","applepay","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","_paymentMethod","verifyCheckoutSpamProtection","_applePayButton","_createButton","addEventListener","_handleWalletButtonClick","gateway","BRAINTREE","_initializeBraintreeSdk","getElementById","button","setAttribute","event","preventDefault","getCartOrThrow","getCheckoutOrThrow","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","requiredBillingContactFields","requiredShippingContactFields","countryCode","label","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","_onValidateMerchant","merchantSession","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","loadCheckout","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","consignments","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","Array","completeShippingContactSelection","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","location","hostname","bigPayEndpoint","paymentsUrl","billingContact","_getBraintreeDeviceData","deviceSessionId","formattedPayload","apple_pay_token","payment_data","payment_method","transaction_id","transactionIdentifier","transformedBillingAddress","transformedShippingAddress","emailAddress","phone","phoneNumber","updateBillingAddress","submitOrder","useStoreCredit","submitPayment","completePayment","STATUS_SUCCESS","STATUS_FAILURE","contact","firstName","givenName","lastName","familyName","city","locality","company","address1","addressLines","address2","postalCode","stateOrProvince","administrativeArea","stateOrProvinceCode","customFields","braintreePaymentMethod","getPaymentMethod","getHost","createRequestSender","host","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","getCustomerEmail","hasBoltAccount","signInCustomer","signOutCustomer","checkoutPaymentMethodExecuted","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","embeddedOneClickEnabled","callbacks","close","openCheckout","BoltCheckout","BoltDeveloperMode","StyleButtonSize","StyleButtonShape","developerModeParams","cartId","storefrontApiToken","getDomainURL","getScriptOptions","loadBoltEmbedded","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","PAYPAL_COMPONENTS","overlay","dataCollectors","getBraintreeFastlane","cardId","isTestModeEnabled","styles","localStorage","setItem","braintreeFastlane","getSessionId","braintreeFastlaneCreator","defaultStyles","root","backgroundColorPrimary","getPaypal","braintreePaypal","paypal","shouldSaveInstrument","newWindowFlow","supportsPopups","show","focusWindow","tokenize","enableShippingAddress","flow","useraction","getPaypalCheckout","onSuccess","paypalCheckout","paypalCheckoutConfig","paypalCheckoutCallback","braintreePaypalCheckout","paypalSdkLoadConfig","isCreditEnabled","components","intent","commit","loadPayPalSDK","getDataCollector","cacheKey","cached","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","details","split","first_name","last_name","phone_number","address_line_1","address_line_2","country_code","postal_code","mapToLegacyBillingAddress","removeElement","elementId","element","riskCorrelationId","formPoster","braintreeIntegrationService","braintreepaypal","paymentButtonStyles","checkoutTopButtonStyles","paypalCheckoutOptions","paypalCheckoutSuccessCallback","renderPayPalButton","paypalCheckoutErrorCallback","handleError","buttonStyles","fundingSource","FUNDING","PAYPAL","paypalButtonRender","Buttons","style","height","createOrder","setupPayment","onApprove","authorizeData","tokenizePayment","isEligible","render","loadDefaultCheckout","addresses","shippingAddressOverride","createPayment","shippingAddressEditable","offerCredit","tokenizePayload","nonce","postForm","payment_type","provider","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","createFormPoster","braintreepaypalcredit","hasRenderedSmartButton","PAYLATER","CREDIT","namespace","getItem","rawValue","withNamespace","removeItem","getItemOnce","isInvalidStyleOption","styleOption","getFastlaneStyles","styleSettings","uiStyles","fastlaneStyles","omitBy","input","toggle","textBody","text","textCaption","caption","branding","cleanUpFastlaneStyles","fastlaneRootSettingsBackgroundColor","errorColor","fastlaneRootSettingsErrorColor","fontFamily","fastlaneRootSettingsFontFamily","fontSizeBase","fastlaneRootSettingsFontSize","padding","fastlaneRootSettingsPadding","primaryColor","fastlaneRootSettingsPrimaryColor","borderRadius","fastlaneInputSettingsBorderRadius","borderColor","fastlaneInputSettingsBorderColor","focusBorderColor","fastlaneInputSettingsFocusBorderBase","backgroundColor","fastlaneInputSettingsBackgroundColor","borderWidth","fastlaneInputSettingsBorderWidth","textColorBase","fastlaneInputSettingsTextColorBase","colorPrimary","fastlaneToggleSettingsColorPrimary","colorSecondary","fastlaneToggleSettingsColorSecondary","color","fastlaneTextBodySettingsColor","fontSize","fastlaneTextBodySettingsFontSize","fastlaneTextCaptionSettingsColor","fastlaneTextCaptionSettingsFontSize","fastlaneBrandingSettings","mergeFastlaneStyles","braintreeFastlaneUtils","isAcceleratedCheckoutEnabled","braintreefastlane","getValidPaymentMethodOrThrow","isFastlaneStylingEnabled","paypalFastlaneStylesSettings","initializeBraintreeFastlaneOrThrow","getCustomerOrThrow","shouldRunAuthenticationFlow","runPayPalAuthenticationFlowOrThrow","primaryMethodId","shouldRunAcceleratedCheckout","validPaymentMethodId","UntrustedShippingCardVerificationType","browserStorage","getDeviceSessionId","getBraintreeFastlaneOrThrow","getBraintreeFastlaneComponentOrThrow","FastlaneCardComponent","shouldSetShippingOption","getMethodIdOrThrow","identity","lookupCustomerByEmail","triggerAuthenticationFlow","isFastlaneShippingOptionAutoSelectEnabled","customerEmail","customerContextId","updatePaymentProviderCustomer","authenticationState","UNRECOGNIZED","instruments","profileData","CANCELED","shippingAddresses","mapPayPalToBcAddress","paypalBillingAddress","getPayPalBillingAddresses","billingAddresses","card","mapPayPalToBcInstrument","mergeShippingAndBillingAddresses","digitalItems","digitalItemBilling","setShippingOption","map","instrument","brand","expiry","lastDigits","expiryYear","bigpayToken","defaultInstrument","expiryMonth","iin","last4","trustedShippingAddress","untrustedShippingCardVerificationMode","PAN","phones","countries","getCountries","Date","now","streetAddress","extendedAddress","country","countryCodeAlpha2","matchedCountry","paymentSource","given_name","surname","normalizeAddress","omit","filteredBillingAddresses","some","getConsignments","recommendedShippingOption","braintreeSdk","buttonClassName","visaCheckoutOptions","braintreeVisaCheckout","visaCheckoutInstance","initOptions","createInitOptions","paymentRequest","String","settings","locale","storeLanguage","shipping","collectShipping","signInButton","createSignInButton","init","on","paymentSuccessPayload","visibility","getShippingAddress","billing","mapToVisaCheckoutAddress","userData","cardInformation","userEmail","card_information","cardType","number","lastTwo","getAddress","buttonClass","insertVisaCheckoutButton","buttonTemplate","visaCheckoutButton","display","flexDirection","width","className","innerHTML","hostWindow","target","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","_decimalPlaces","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","format","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","_toFixed","integerAmount","decimalAmount","parsedIntegerAmount","replace","toLowerCase","precision","round","_storeConfig","_customerFormatter","shopperCurrency","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","CurrencyService","lineItem","isShippingRequired","customItems","PayPalCommerceIntent","StyleButtonLabel","StyleButtonColor","GooglePayCardNetwork","CallbackIntentsType","CallbackTriggerType","isGooglePayCardNetworkKey","_gatewayIdentifier","_isBuyNowFlow","mapToShippingAddressRequestBody","_mapToAddressRequestBody","mapToBillingAddressRequestBody","paymentMethodData","mapToExternalCheckoutData","cart_id","getRequiredData","data","emailRequired","_isShippingAddressRequired","loadShippingCountries","allowedCountryCodes","getShippingCountries","shippingAddressRequired","shippingAddressParameters","phoneNumberRequired","shippingOptionRequired","getCallbackIntents","OFFER","SHIPPING_ADDRESS","SHIPPING_OPTION","getCallbackTriggers","availableTriggers","INITIALIZE","initializationTrigger","addressChangeTriggers","shippingOptionsChangeTriggers","getNonce","extraPaymentData","getMerchantInfo","getGooglePayInitializationData","merchantName","authJwt","getTransactionInfo","_getCurrencyCodeOrThrow","storeCountry","totalPriceStatus","ESTIMATED","totalPrice","getPaymentGatewayParameters","gatewayMerchantId","getCardParameters","allowedAuthMethods","allowedCardNetworks","supportedCards","billingAddressRequired","billingAddressParameters","_getPaymentMethodFn","_currencyCode","handleShippingAddressChange","mappedShippingAddress","consignment","_currencyService","_getGooglePayShippingOption","shippingOption","selectedShippingOptionId","handleShippingOptionChange","defaultSelectedOptionId","getTotalPrice","getGatewayIdentifier","setGatewayIdentifier","getStoreConfig","address3","_getFirstAndLastName","trim","fullName","nameParts","slice","isGooglePayErrorObject","GooglePayKey","isGooglePayKey","values","_googlePayPaymentProcessor","_methodId","googlePayOptions","_getMethodId","_getGooglePayClientOptions","_addPaymentButton","_paymentButton","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","shippingOptionData","newTransactionInfo","FINAL","newShippingOptionParameters","buttonType","addPaymentButton","_handleClick","initializeWidget","_interactWithPaymentSheet","err","statusCode","showPaymentSheet","siteLink","pathname","links","setExternalCheckoutForm","_scriptLoader","_gateway","_formPoster","_baseRequest","apiVersion","apiVersionMinor","googlePayPaymentOptions","getGooglePaymentsClient","_paymentsClient","_buildButtonPayloads","_buildWidgetPayloads","_determineReadinessToPay","_prefetchGooglePaymentData","paymentButton","_getPaymentsClient","allowedPaymentMethods","_getBaseCardPaymentMethod","paymentDataRequest","_getPaymentDataRequest","loadPaymentData","setExternalCheckoutXhr","_setExternalCheckout","processAdditionalAction","useFormPoster","transactionInfo","prefetchPaymentData","isReadyToPay","_getIsReadyToPayRequest","_baseCardPaymentMethod","parameters","baseCardPaymentMethod","_cardPaymentMethod","tokenizationSpecification","merchantInfo","_paymentDataRequest","callbackIntents","_isReadyToPayRequest","_getOrThrow","_window","google","payments","api","PaymentsClient","environment","createGooglePayScriptLoader","requestSender","service","isGooglePayAuthorizeNetInitializationData","assertsIsGooglePayAuthorizeNetInitializationData","paymentGatewayId","assertIsGooglePayCheckoutComInitializationData","isGooglePayCheckoutComInitializationData","_resolve","threeDSBody","three_ds_result","acs_url","isGooglePayThreeDSecureResult","isGooglePayTokenObject","assertIsGooglePayTokenObject","_tokenize","checkoutcomkey","token_data","Authorization","Json","invalidFields","assertsIsGooglePayStripeInitializationData","isGooglePayStripeInitializationData","isGooglePayStripeTokenObject","assertIsGooglePayStripeTokenObject","stripeVersion","stripePublishableKey","stripeConnectedAccount","isStripeGooglePay3dsExperimentIsOn","loadStripeJs","stripeUPEClient","clientSecret","catchedConfirmError","confirmCardPayment","retrievePaymentIntent","_throwDisplayableStripeError","_isCancellationError","paymentIntent","getStripeClient","stripeError","payment_intent","last_payment_error","indexOf","stripeWindow","stripeAccount","stripeClient","bcStripeClient","stripe","betas","Stripe","promise","cancellable","cancel","race","_service","_braintreeGooglePayment","bin","isThreeDSecureEnabled","isNetworkTokenized","orderAmount","getOrderOrThrow","_braintreePresent3DSChallenge","isGooglePayBraintreeTokenObject","assertIsGooglePayBraintreeTokenObject","androidPayCards","createPaymentDataRequest","cardRequirements","billingAddressFormat","paymentMethodTokenizationParameters","verifyCard","onLookupComplete","_data","paypalCommerceScriptLoader","isGooglePayPaypalCommercePaymentMethod","assertsIsGooglePayPayPalCommercePaymentMethod","getPayPalSDK","getGooglePayConfigOrThrow","googlepayConfig","initializesOnCheckoutPage","forceLoad","paypalSdkScriptConfig","getPayPalSdkScriptConfigOrThrow","Googlepay","transformConfig","scriptQuery","URLSearchParams","scriptSrc","clientId","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","isGooglePayEnabled","shouldEnableCard","enableCardFunding","disableCardFunding","cardFieldsComponent","enableCreditFunding","disableCreditFunding","shouldEnableAPMs","enableVenmoFunding","disableVenmoFunding","enableAPMsFunding","disableAPMsFunding","apm","disableFunding","enableFunding","googlePayComponent","transformedConfig","isArray","getBrowserInfo","language","navigator","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","getTimezoneOffset","browser_info","errorBody","isObject","isTdOnlineMartAdditionalAction","threeDSResult","formUrl","threeDSSessionData","creq","CartSource","LiabilityShiftEnum","NonInstantAlternativePaymentMethods","PayPalOrderStatus","paypalCommerceRequestSender","loadPayPalSdk","providedCurrencyCode","paypalSdk","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","requestBody","createOrderCardFields","orderId","setupToken","updateOrder","getConsignmentsOrThrow","getOrderStatus","order_id","source","BuyNow","gatewayId","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","shippingOptionToSelect","getBillingAddressFromOrderDetails","payer","email_address","admin_area_2","admin_area_1","getShippingAddressFromOrderDetails","orderDetails","getValidButtonStyle","shape","validStyles","getValidHeight","isNil","paypalCommerceIntegrationService","paypalcommerce","onComplete","defaultCallbacks","orderID","hostedCheckoutCallbacks","onShippingAddressChange","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","paypalButton","order","paypalcommercecredit","paypalCommerceCredit","fundingSources","paypalcommercevenmo","VENMO","getPayPalFastlaneSdk","paypalFastlaneSdk","getPayPalFastlaneSdkConfiguration","getPayPalApmsSdk","paypalApms","getPayPalApmSdkConfiguration","getPayPalMessages","paypalMessages","paypalSdkMessagesConfig","getPayPalSdkMessagesConfiguration","scriptOptions","scriptAttributes","connectClientToken","createPayPalCommerceSdk","createScriptLoader","PayPalFastlaneAuthenticationState","initializePayPalFastlane","paypalFastlane","getPayPalFastlaneOrThrow","lookupCustomerOrThrow","triggerAuthenticationFlowOrThrow","updateStorageSessionId","shouldBeRemoved","getStorageSessionId","mapPayPalFastlaneProfileToBcCustomerData","authenticationResult","paypalShippingAddress","paypalProfileName","paypalInstrument","filterAddresses","mapBcToPayPalAddress","addressLine1","addressLine2","adminArea1","adminArea2","profileName","phoneData","nationalNumber","customerAddresses","currentAddress","customerAddress","isEqualAddresses","firstAddress","secondAddress","createPayPalCommerceFastlaneUtils","paypalCommerceSdk","paypalCommerceFastlaneUtils","paypalcommercefastlane","isAuthenticationFlowCanceled","updateCustomerDataState","updatedState","firstShippingOption","shippingOptionId","isStripeAcceleratedCheckoutCustomer","isStripeUPEPaymentMethodLike","shopperLanguage","StripeFormMode","DisplayName","StripePaymentMethodType","StripeStringConstants","StripeElementType","StripeUPEPaymentIntentStatus","stripeupe","onEmailChange","getStyles","isLoading","paymentProviderCustomer","getPaymentProviderCustomerOrThrow","stripePaymentProviderCustomer","stripeLinkAuthenticationState","appearance","variables","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","fieldBorder","fieldText","boxShadow","getElements","_stripeElements","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","authenticated","deleteConsignment","mount","unmount","stripeElements","bcStripeElements","elements","updateStripeElements","update","fetchUpdates","createCustomerStrategyRegistry","customerStrategyFactories","registry","createCustomerStrategy","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerActionType","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","createAccount","switchMap","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","CreateCustomerAddressRequested","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","SignInCustomerRequested","SignInCustomerSucceeded","SignInCustomerFailed","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerStrategyActionType","_strategyRegistry","_strategyRegistryV2","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","SignOutRequested","SignOutSucceeded","SignOutFailed","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","includesDictionary","deletions","pickBy","additions","difference","mergeIncludes","updateCheckout","CheckoutActionType","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","_shouldTransformCustomerAddress","_transformCustomerAddresses","LoadCheckoutFailed","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","shouldSaveAddress","FormFieldsActionType","_formFieldsRequestSender","LoadFormFieldsRequested","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","PaymentMethodActionType","isPaymentMethod","loadPaymentMethodsById","methodIds","LoadPaymentMethodsRequested","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","loadPaymentMethods","sessionHash","methods","filteredMethods","_filterApplePay","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","cartA","cartB","_normalize","cartAmount","itemA","itemB","productId","variantId","localeCompare","extendedSalePrice","giftCertificates","recipient","giftWrapping","previous","updated","validate","comparator","_compareCoupons","coupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","_mutationObserver","ensurePresence","targets","mutationsList","mutation","removedNodes","node","contains","observe","childList","subtree","output","disconnect","callback","MutationObserver","parseUrl","anchor","href","port","origin","protocol","search","isIframeEvent","targetOrigin","_targetWindow","_context","_targetOrigin","targetWindow","fromEvent","successType","errorType","take","toPromise","postMessage","setTarget","setContext","appendWww","sourceOrigin","_sourceOrigins","_isListening","_listeners","listen","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","removeListener","index","splice","trigger","messageEvent","_googleRecaptcha","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","additional_action_required","_performRecaptcha","human_verification_token","recaptchaSitekey","cardingProtectionElementId","cardingProtectionElement","parentNode","removeChild","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","event$","Subject","_widgetId","size","getResponse","reset","_event$","_recaptcha","retryWhen","delay","TIMEOUT","_watchRecaptchaChallengeWindow","iframeContainer","parentElement","attributeFilter","_loadPromise","_loadScript","callbackName","grecaptcha","createSpamProtection","MutationObserverFactory","mapFromPaymentErrorResponse","joinErrors","flatMap","fieldErrors","HostedFieldEventType","HostedInputEventType","_type","_containerId","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_cardInstrument","_iframe","src","border","overflow","getType","attach","contentWindow","AttachRequested","accessibilityLabel","cardInstrument","fontUrls","_getFontUrls","placeholder","AttachSucceeded","AttachFailed","detach","submitForm","fields","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","submitStoredCardForm","StoredCardRequested","StoredCardSucceeded","StoredCardFailed","validateForm","ValidateRequested","Validated","isValid","querySelectorAll","link","family","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","_handleEnter","onBlur","onCardTypeChange","onFocus","onValidate","Blurred","CardTypeChanged","Focused","Entered","_cardType","BinChanged","_bin","getBin","getCardType","field","_getFirstField","otherFields","without","otherField","submit","additionalActionData","transform","additionalAction","submitStoredCard","isVaultedInstrument","instrumentId","_store","instrumentMeta","getInstrumentsMeta","getOrder","orderMeta","getOrderMeta","paymentMethodMeta","getPaymentMethodsMeta","authToken","getPaymentToken","vaultAccessToken","fieldOptions","_getCardInstrument","pick","getCardInstrument","MissingPaymentInstrument","OrderActionType","_orderRequestSender","_checkoutValidator","loadOrder","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","loadCurrentOrder","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","checkoutVariant","SubmitOrderSucceeded","SubmitOrderFailed","finalizeOrder","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","PaymentActionType","_paymentRequestSender","_orderActionCreator","_paymentRequestTransformer","initializeOffsitePayment","shouldSetAsDefaultInstrument","bigpay_token","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","SubmitPaymentSucceeded","SubmitPaymentFailed","_client","_transformResponse","statusText","createPaymentClient","paymentClient","setHost","paymentSettings","bigpayBaseUrl","mapToInternalAddress","addressId","isBillingAddressLike","province","provinceCode","postCode","toInteger","couponTypes","mapToInternalCoupon","coupon","discount","displayName","discountType","couponType","mapToInternalGiftCertificate","discountedAmount","used","remainingBalance","remaining","balance","purchaseDate","CheckoutButtonMethodType","mapToInternalLineItems","itemMap","idKey","amountTransformer","imageUrl","amountAfterDiscount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","discountAmount","listPrice","salePrice","downloadsPageUrl","downloadPageUrl","sku","categoryNames","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","promotions","notifications","items","sum","discountNotifications","promotion","banners","banner","placeholders","messageHtml","totalDiscountedAmount","certificate","appliedGiftCertificates","keyBy","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","required","storeCredit","taxSubtotal","taxTotal","handling","handlingCostTotal","mapToInternalCustomer","customerId","customerGroupName","customerGroup","RegExp","month","year","trimmedMonth","trimmedYear","toObject","maxLength","max","creditCardType","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","orderToken","callbackUrl","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmountAsInteger","isDefaultOrderPayment","step","helpText","instructions","returnUrl","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","_cardExpiryFormatter","_cardNumberFormatter","formattedInstrument","_mapShippingAddress","getShippingOption","contextConfig","paymentMeta","internalCustomer","_transformPaymentMethod","quoteMeta","geoCountryCode","transformWithHostedFormData","_transformHostedInputValues","BRAINTREE_VENMO","BRAINTREE_PAYPAL","ccCvv","cardCodeVerification","ccNumber","cardNumberVerification","hostedFormNonce","cardCode","ccExpiry","cardExpiry","ccName","cardName","cardNumber","isBopisEnabled","bopis","enabled","requiredAddress","isPickup","every","selectedPickupOption","PaymentProviderCustomerType","providerCustomerData","UpdatePaymentProviderCustomer","PaymentStrategyActionType","RemoteCheckoutActionType","_remoteCheckoutRequestSender","initializeBilling","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","initializeShipping","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","initializePayment","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","loadSettings","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","forgetCheckout","ForgetCheckoutRemoteCustomerRequested","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","methodName","generateToken","trackAuthorizationEvent","ConsignmentActionType","_consignmentRequestSender","unassignItemsByAddress","_consignmentHasAddress","existingConsignment","getConsignmentByAddress","_removeLineItems","updateConsignment","assignItemsByAddress","_createOrUpdateConsignment","_addLineItems","consignmentUpdateBody","consignmentMeta","UpdateShippingOptionRequested","UpdateShippingOptionSucceeded","UpdateShippingOptionFailed","loadShippingOptions","LoadShippingOptionsRequested","LoadShippingOptionsSucceeded","LoadShippingOptionsFailed","_getUpdateAddressRequestBody","createConsignments","CreateConsignmentsRequested","CreateConsignmentsSucceeded","CreateConsignmentsFailed","UpdateConsignmentRequested","UpdateConsignmentSucceeded","UpdateConsignmentFailed","consignmentId","DeleteConsignmentRequested","DeleteConsignmentSucceeded","DeleteConsignmentFailed","updateShippingOption","_isUpdateConsignmentRequest","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","DEFAULT_INCLUDES","ShippingCountryActionType","_shippingCountryRequestSender","loadCountries","checkoutData","channelId","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","_config","channelIdParam","SpamProtectionActionType","spamProtectionElementId","spamProtectionElement","googleRecaptchaSitekey","VerifyCheckoutRequested","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","ExecuteSucceeded","ExecuteFailed","StoreCreditActionType","_storeCreditRequestSender","applyStoreCredit","ApplyStoreCreditRequested","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","SubscriptionsActionType","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","isPlainObject","cloneDeep","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getBillingAddressOrThrow","getOutstandingBalance","getLocale","getCardInstrumentOrThrow","getInstruments","getPaymentTokenOrThrow","getPaymentIdOrThrow","getPaymentStatus","getPaymentStatusOrThrow","getPaymentRedirectUrl","getPaymentRedirectUrlOrThrow","isPaymentDataRequired","getPaymentProviderCustomer","isPaymentMethodInitialized","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","_storeProjectionFactory","_hostedFormFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_paymentActionCreator","_customerActionCreator","_cartRequestSender","_storeCreditActionCreator","_paymentProviderCustomerActionCreator","_shippingCountryActionCreator","_remoteCheckoutActionCreator","_paymentStrategyWidgetActionCreator","_storeProjection","createHostedForm","subscriber","filters","initializeOffsitePaymentConfig","buyNowCartRequestBody","validateCheckout","handlePaymentHumanVerification","queueId","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","checkoutValidator","hostedFormFactory","orderActionCreator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentActionCreator","paymentHumanVerificationHandler","customerActionCreator","storeCreditActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","paymentProviderCustomerActionCreator","shippingCountryActionCreator","remoteCheckoutActionCreator","paymentStrategyWidgetActionCreator","_braintreeScriptLoader","_dataCollectors","_clientToken","_getPayPalSDKConfig","_paypalCheckout","getVenmoCheckout","_venmoCheckout","venmoCheckoutCallback","get3DS","_3ds","getVisaCheckout","_visaCheckout","createHostedFields","_teardown","mod","_braintreeSDKCreator","handleSuccess","tokenizedPayload","_toVisaCheckoutAddress","_postForm","_getCardInformation","_getAddress","createBraintreeVisaCheckoutPaymentProcessor","braintreeSDKCreator","useMasterpassSrc","subdomain","sourceUrl","masterpass","_customerStrategyActionCreator","_braintreeVisaCheckoutPaymentProcessor","_visaCheckoutScriptLoader","_buttonClassName","_createSignInButton","_paymentInstrumentSelected","_onPaymentSelectComplete","_insertVisaCheckoutButton","getCallbackUrl","supportedLocales","es","en","pt","zu","ar","zh","ms","sv","hr","pl","nl","it","fr","formatLocale","localeLanguage","formattedLocale","countryLocales","_masterpassScriptLoader","_locale","masterpassOptions","allowedCardTypes","suppressShippingAddress","masterpassScriptLoaderParams","isMasterpassSrcEnabled","Masterpass","_signInButton","ExtensionActionType","ExtensionInternalEventType","createExtensionEventPoster","extension","iframe","ExtensionNotFoundError","iframeResizer","originalIframeResizer","ExtensionInternalCommandType","_options","createFrame","initCallback","failedCallback","ExtensionNotLoadedError","_toResizableFrame","timeoutInterval","detachmentObserver","setTimeout","handleMessage","ResizeIframe","iframes","autoResize","scrolling","sizeWidth","heightCalculationMethod","clearTimeout","ExtensionCommandType","_extension","parentOrigin","_url","URL","searchParams","iframeCreator","iframeResizerCallback","ExtensionReady","ExtensionFailed","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","checkoutLink","getExtensionByRegion","RenderExtensionRequested","ExtensionIframe","RenderExtensionSucceeded","RenderExtensionFailed","ExtensionEventType","_posters","extensionId","command","commandHandler","_getExtensionById","validCommandType","_validateCommand","commandHandlerProxy","getExtensions","_extensions","UnsupportedExtensionCommandError","_extensionMessenger","_subscribers","_subscribed","_unsubscribers","eventListener","Subscribe","_handleSubscribe","Unsubscribe","_handleUnsubscribe","broadcast","eventType","subscribeConsignmentsChange","broadcaster","getInitialConsignments","currentConsignments","ConsignmentsChanged","previousConsignments","_stylesheetLoader","configuration","loadStylesheet","prepend","AdyenCheckout","AdyenV3ActionType","AdyenV2ActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenCardFields","isCardState","encryptedSecurityCode","encryptedExpiryMonth","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","translations","_adyenClient","_mountPaymentComponent","_paymentComponent","CreditCard","Bancontact","_mountCardVerificationComponent","_cardVerificationComponent","_validateCardData","componentState","_componentState","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","_processAdditionalAction","credit_card_token","finalize","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentPayload","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","street","houseNumberOrName","holderName","cardVerificationComponent","adyenClient","cardVerificationContainerId","SecuredFields","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","cardComponent","componentRef","showValidation","issuer","props","_mapCardErrors","cardStateErrors","getStylesheetLoader","isHostedInstrumentLike","adyenv3","installmentOptions","paymentMethodsConfiguration","klarna","useKlarnaWidget","klarna_account","klarna_paynow","showInstallmentAmounts","showPayButton","paymentToken","socialSecurityNumber","shopperName","isBoletoState","installments","plan","onActionHandled","componentType","challengeWindowSize","ThreeDS2","Sdk","_mountElement","showBrandsUnderCardNumber","showEmailAddress","onSubmit","adyenComponent","affirmScriptLoader","affirm","initializeAffirmCheckout","affirmCheckout","checkout_token","getCheckoutInformation","open","onFail","failObject","reason","successObject","ui","retrievedShippingAddress","merchant","user_confirmation_url","user_cancel_url","user_confirmation_url_action","getItems","metadata","shipping_type","getShippingType","platform_type","platform_version","platform_affirm","discounts","getDiscounts","shipping_amount","tax_amount","first","last","full","zipcode","display_name","unit_price","qty","item_image_url","item_url","categories","getCategories","line","discount_amount","discount_display_name","DISCOUNTED_AMOUNT","categoryTree","category","AFFIRM_SCRIPTS","affirmWindow","apikey","scriptURI","SANDBOX","PROD","m","g","h","k","p","getElementsByTagName","l","c","arguments","f","a1","c1","a2","c2","insertBefore","public_api_key","script","_afterpayScriptLoader","_mapCurrencyToISO2","_afterpaySdk","_loadPaymentMethod","_redirectToAfterpay","redirect","AUD","NZD","CAD","USD","SCRIPTS_DEFAULT","SCRIPTS_US","_getScriptURI","isAfterpayWindow","AfterPay","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","toUpperCase","redirect_url","_getAmazonPayButton","click","isModalFlow","clone","cloneNode","replaceChild","_showLoadingSpinner","_storeCreditLabel","StoreCredit","storeCreditLabel","isStoreCreditApplied","min","BRAINTREE_FASTLANE","blueSnapSdk","_blueSnapSdk","initialize3ds","cardData","_getBlueSnapSdk","threeDsPaymentsSetup","sdkResponse","threeDSecureReferenceId","threeDsPaymentsSubmitData","HostedFieldType","isHostedCardFieldOptionsMap","CardNumber","isHostedStoredCardFieldOptionsMap","CardCodeVerification","CardNumberVerification","_blueSnapDirectHostedForm","_blueSnapDirect3ds","creditCard","is3dsEnabled","_paymentFieldsToken","_shouldUseHostedFields","form","_getPaymentFieldsToken","pfToken","_getBlueSnapDirectThreeDSecureData","bluesnapSubmitedForm","previouslyUsedCard","last4Digits","ccType","cardHolderName","billingFirstName","billingLastName","billingCountry","billingCity","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingCity","shippingZip","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapHostedFieldType","CardExpiry","CardName","CardCode","CREDIT_CARD_ERRORS","fieldType","invalid","_nameOnCardInput","_hostedInputValidator","initializeValidationFields","paymentFieldsToken","enable3DS","callbacksAndStyles","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","THREE_DS_AUTH_FAILED","errorDescription","getValue","onEnter","onFieldEventHandler","setupComplete","_usetUiEventCallback","_handleError","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","kebabCase","errorCode","eventOrigin","INVALID_OR_EMPTY","EMPTY","INVALID","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","_errors","_updateErrors","errorData","_style","_create","_getInput","_handleFocus","_handleBlur","_input","_applyStyles","HTMLInputElement","ON_BLUR","allowedStyle","fontWeight","styleKeys","_configureInput","autocomplete","inputMode","margin","outline","BlueSnapDirectSdkEnv","PRODUCTION","_formatePaymentPayload","_isBlueSnapDirectRedirectResponse","providerData","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerDataQuery","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","sepa_direct_debit","iban","isIdealInstrument","ideal","bic","isPayByBankInstrument","pay_by_bank","partialResponse","partialBody","PaymentStatusTypes","orderRequest","_initializeOptions","frame","_createIframe","ACKNOWLEDGE","FINALIZE","bluesnapv2","storage","saveExtraItemsData","getStorageKey","readExtraItemsData","itemsData","hasNotExtraItems","isExtraItemsData","clearExtraItemData","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","success","transaction","reference","configure","boltTransaction","validateTokenizeResultOrThrow","tokenizeResult","last_four_digits","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","getTransactionReference","transactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","Number","isNaN","isAnalyticsEnabled","isUsBankAccountInstrumentLike","braintreeach","getMandateText","handleBraintreeError","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","submitPaymentPayload","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","tokenized_bank_account","masked_account_number","ownershipType","businessName","_createElements","closeElement","mainElement","_element","_closeElement","_mainElement","_registerClick","opacity","_unregisterClick","_removeAfterTransition","classLayout","classClose","classOverlayText","background","transitionDuration","hasCloseButton","innerHtml","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","handleTransition","propertyName","DEFAULT_STYLES","ROTATION_ANIMATION","containerStyles","defineAnimation","buildContainer","indicator","buildIndicator","parentId","hide","handleTransitionEnd","bottom","left","position","right","top","transition","setStyleAttribute","transformStyle","animation","attrs","setProperty","head","sheet","CSSStyleSheet","insertRule","LOADING_INDICATOR_STYLES","loadingIndicator","braintreeOptions","bannerContainerId","loadPaypalCheckoutInstance","shouldHandleInstrumentDeclinedError","isProviderError","braintreeTokenizePayload","vaultPaymentInstrument","enableCheckoutPaywallBanner","renderPayPalMessages","onPaymentError","onRenderButton","loadingIndicatorContainer","toggleLoadingIndicator","tokenizePaymentOrThrow","onCancel","Messages","layout","logo","isBraintreePaypalProviderError","provider_error","isLPMsUpdateExperimentEnabled","braintreelocalmethods","isNonInstantPaymentMethod","executeWithNotInstantLPM","executeWithInstantLPM","getLPMsBasicPaymentData","basicPaymentData","isBraintreeRedirectError","startPayment","getInstantLPMConfig","getInstantLPMCallback","paymentType","fallback","buttonText","onPaymentStart","start","paymentId","isBraintreeOrderSavedResponse","order_id_saved_successfully","startPaymentError","payloadData","isBraintreeAcceleratedCheckoutCustomer","paypalFastlaneStyleSettings","initializeCardComponent","renderBraintreeCardComponent","handleBraintreeStoredInstrumentChange","preparePaymentPayload","braintreeCardComponent","cardComponentOptions","cardholderName","prefill","paypalPaymentComponent","getBraintreeCardComponentOrThrow","getPayPalInstruments","paypal_fastlane_token","mapToPayPalAddress","braintreePaymentProviderCustomer","paypalFastlaneSessionId","profile","showCardSelector","selectionChanged","selectedCard","braintreeFastlaneCustomer","selectedInstruments","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","formOptions","_hostedForm","isHostedFormEnabled","AdditionalActionType","_processResponse","additionalActionRequired","OffsiteRedirect","_performRedirect","_createFormattedPayload","fawryPaymentData","customerMobile","isThreeDSecureRequiredError","_handleThreeDSecure","payer_auth_request","callback_url","merchant_data","PaReq","TermUrl","MD","DOCUMENT_SUPPORTED_APMS","ccDocument","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","_getScriptUrl","_cardinalClient","prepare","_getClientToken","hostedForm","runBinProcess","getThreeDSecureData","_getOrderData","CardinalEventType","CardinalInitializationType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalSignatureValidationErrors","_provider","_testMode","_configurationToken","_sdk","_getClientSDK","SetupCompleted","off","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Yes","Failure","continueObject","AcsUrl","Payload","partialOrder","_mapToPartialOrder","continue","CCA","transactionId","consumer","BillingAddress","_mapToCardinalAddress","Account","_mapToCardinalAccount","Email1","ShippingAddress","Consumer","OrderDetails","OrderNumber","Amount","CurrencyCode","OrderChannel","TransactionId","AccountNumber","ExpirationMonth","ExpirationYear","NameOnAccount","cardinalAddress","FirstName","LastName","Address1","City","State","PostalCode","CountryCode","Address2","Phone1","Cardinal","_threeDSecureFlow","xid","_getBin","_submitPayment","threeDsResult","threeDsToken","isCreditCardInstrument","hostedFormBin","AuthenticationSourceStatus","digitalRiverScriptLoader","digitalRiverInitializeOptions","digitalriver","publicKey","getDigitalRiverInitializeOptions","digitalRiverJS","unsubscribe","loadWidget","digitalRiverCheckoutData","submitVaultedInstrument","isAuthenticateSourceAction","authenticateSource","loadSuccessResponse","readyForStorage","getDigitalRiverJs","onSuccessResponse","submitFormEvent","browserInfo","owner","reusable","billingAddressPayPal","onReadyResponse","paymentMethodConfiguration","mountComplianceSection","sellingEntity","onSubmitForm","disabledPaymentMethods","digitalRiverConfiguration","showSavePaymentAgreement","onReady","descriptiveError","digitalRiverDropComponent","createDropin","sourceId","source_id","sourceClientSecret","source_client_secret","authenticateSourceResponse","failed","authentication_not_required","confirm","complianceDiv","complianceOptions","classes","base","compliance","entity","drfooter","cssText","classList","add","stylesheetLoader","DigitalRiver","_isAdditionalActionRequired","redirectUrl","isAdditionalActionRequiredErrorResponse","googlePayToken","walletButton","extraData","_clickListener","ConfirmOrderStatus","_paypalCommerceScriptLoader","getOrderId","confirmOrderData","tokenizationData","cardNetwork","cardDetails","confirmOrder","payPalSDK","PayerActionRequired","initiatePayerAction","Approved","requestData","processable","isOffsiteRedirectResponse","handleOffsiteRedirectResponse","supportedCountries","supportedCountriesRequiringStates","klarnaScriptLoader","klarnaCredit","authorize","authorizationToken","client_token","getUpdateSessionData","mapToKlarnaAddress","needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","res","approved","show_form","klarnaWindow","Credit","klarnav2ScriptLoader","klarnav2TokenUpdater","klarnaPayments","loadPaymentsWidget","klarnaOrderInitialization","authorizeOrThrow","klarnav2","updateClientToken","payment_method_category","Payments","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","mollieScriptLoader","mollie","controllers","each","controller","initializeOptions","isCreditCard","shouldShowTSVHostedForm","mountCardVerificationfields","loadMollieJs","mollieClient","mountElements","disableButton","loadPaymentMethodsAllowed","executeWithVaulted","executeWithCC","executeWithAPM","cardHolderElement","cardNumberElement","verificationCodeElement","expiryDateElement","getMollieClient","createToken","shopper_locale","getShopperLocale","isHostedPaymentFormEnabled","CREDIT_CARD","isHostedFieldAvailable","getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","mollieHostWindow","isMollieWindow","Mollie","monerisOptions","profileId","createIframe","windowEventListener","instrumentSettings","frameref","monerisURL","handleMonerisResponse","definedFields","monerisQueryParams","pmmsg","display_labels","enable_exp","enable_cvd","css_body","cssBody","css_textbox","cssTextbox","css_textbox_pan","cssTextboxCardNumber","css_textbox_exp","cssTextboxExpiryDate","css_textbox_cvd","cssTextboxCVV","css_input_label","cssInputLabel","pan_label","creditCardLabel","exp_label","expiryDateLabel","cvd_label","cvdLabel","queryString","monerisResponse","responseCode","errorMessage","dataKey","orderPayload","_shouldSubmitFullPayload","shouldRenderPayPalButtonOnInitialization","isPayPalVaultedInstrumentPaymentData","prepareVaultedInstrumentPaymentPayload","paypalOrderId","shouldConfirmInstrument","isTrustedVaultingFlow","checkoutPaymentButtonStyles","handleClick","handleApprove","fieldsValues","getFieldsValues","isPaypalCommerceProviderError","messagesStyles","ratio","paypalOptions","paypalBNPLConfiguration","bannerConfiguration","renderMessages","onValidationPassed","paypalMessagesOptions","paypalcommercealternativemethods","shouldRenderFields","renderFields","paypalAmpsSdk","getPaypalAmpsSdkOrThrow","buttonStyle","onInitButton","onCreateOrder","handleFailure","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","fieldsOptions","PaymentFields","isCreditCardFormFields","isCreditCardVaultedFormFields","CardExpiryVerification","isPayPalCommerceAcceleratedCheckoutCustomer","paypalcommercecreditcards","onCreditCardFieldsRenderingError","hostedFormOptions","isCreditCardForm","isCreditCardVaultedForm","hasUndefinedValues","initializeFields","shouldInitializePayPalFastlane","initializePayPalFastlaneOrThrow","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","getInstrumentParams","returnedOrderId","returnedVaultedToken","cvvField","expiryField","numberField","nameField","verification_nonce","card_with_order","executeCallback","getExecuteCallback","cardFieldsConfig","getInputStyles","vaultSetupToken","liabilityShift","No","Unknown","inputEvents","onChangeHandler","onFocusHandler","onBlurHandler","onInputSubmitRequest","CardFields","cardFields","stylizeInputContainers","renderVaultedFields","createVaultSetupTokenCallback","createOrderCallback","createVaultSetupToken","getCardFieldsOrThrow","CVVField","ExpiryField","NameField","NumberField","cardExpiryVerification","getFieldTypeByEmittedField","emittedBy","mapFieldType","submitConfig","cardFieldsState","validationData","getValidityData","mapValidationErrors","updatedFields","cardNameField","fieldsKeys","fieldsErrors","getInvalidErrorByFieldType","validationErrors","commonStyles","marginBottom","marginLeft","paypalCommercePaymentProviderCustomer","isPayPalCommerceAnalyticsV2Enabled","payPalFastlaneSdk","pollingInterval","maxPollingIntervalTime","pollingTimer","stopPolling","paypalcommerceratepay","legalTextContainer","loadingContainerId","createFraudNetScript","loadFraudnetConfig","renderLegalText","metadataId","guid","ratepayBirthDate","ratepayPhoneNumber","ratepayPhoneCountryCode","rate_pay","birth_date","normalizeDate","national_number","initializePollingMechanism","fraudNetScript","fraudNetConfig","deinitializePollingMechanism","legalTextContainerElement","date","formattedDate","formatDate","getDate","formattedMonth","getMonth","getFullYear","legalTextContainerElementId","legalTextContainerId","buttonContainer","buttonContainerParent","ratePayButton","Legal","PAY_UPON_INVOICE","resetPollingMechanism","scriptElement","generateGUID","s","i","floor","characters","reinitializeStrategy","resolvePromise","rejectPromise","useMetadata","orderStatus","isOrderApproved","PollingStop","isPollingError","PollingError","isPayPalFastlaneCustomer","paypalFastlaneStyling","initializePayPalPaymentComponent","renderPayPalPaymentComponent","handlePayPalStoredInstrumentChange","isVaultedFlow","paypalFastlaneCustomer","paypalComponentMethods","getPayPalComponentMethodsOrThrow","selectedInstrument","threeDSecureFlow","_isThreeDSTwoExperimentOn","newPaymentData","SquareIntent","applicationId","locationId","square","_payments","_formValidationSubscription","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","verifyBuyer","CHARGE","_chargeVerifyBuyer","_storeVerifyBuyer","blacklist","Set","eventObservables","isCompletelyValid","distinctUntilChanged","_mapToSquareBillingContact","STORE","_squareV2PaymentProcessor","squarev2","_getVaultedInstrumentPayload","_getCardPayload","_shouldVerify","cardTokenizationResult","tokenData","tokenForSavingCard","store_card_nonce","store_card_token","_getSquareCardIdOrThrow","verificationToken","three_d_secure","SquareV2WebPaymentsSdkEnv","LIVE","isSquareV2Window","assertSquareV2Window","Square","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","IconStyle","StripeV3ErrorType","AuthFailure","APM_REDIRECT","Alipay","stripev3","isDeinitialize","useIndividualCardFields","stripeV3Client","mountCardVerificationFields","mountCardFields","stripeElement","shouldSubmitOrderBeforeLoadingAPM","confirmStripePayment","buildPaymentPayload","handleEmptyPaymentIntentError","unmountElement","isCancellationError","isAuthError","getStripeJs","confirmAlipayPayment","return_url","handleActions","mapStripePaymentData","confirmIdealPayment","Sepa","confirmSepaDebitPayment","getStripeCardElements","getStripeElement","billingDetails","mapStripeBillingDetails","createPaymentMethod","billing_details","stripeCardElements","mapStripeAddress","zipCodeElementOptions","stripePaymentMethodType","cardExpiryElement","cardCvcElement","CardCvc","isAdditionalActionError","needsConfirm","isMounted","checkoutEventsUnsubscribe","initCheckoutEventsSubscription","paymentElement","PAYMENT","updateStripePaymentIntent","mountElement","mapAppearanceVariables","colorIcon","mapInputAppearanceRules","throwStripeError","throwDisplayableStripeError","throwPaymentConfirmationProceedMessage","isPaymentCompleted","SUCCEEDED","_mapStripeAddress","IF_REQUIRED","confirmParams","payment_method_data","isRedirectAction","isOnPageAdditionalAction","bg","cs","da","el","et","fi","fil","he","hu","ja","ko","lt","lv","mt","nb","ro","ru","sk","sl","th","tr","vi","SOFORT","EPS","GRABPAY","BANCONTACT","GIROPAY","ALIPAY","KLARNA","stripeUPEIntegrationService","_loadStripeElement","_stripeUPEClient","_executeWithVaulted","_executeWithStripeConfirmation","_executeWithAPM","_executeWithoutRedirect","_getPaymentPayload","_processAdditionalActionWithStripeConfirmation","_processVaultedAdditionalAction","initStripeElementUpdateTrigger","_loadStripeJs","_isStripeElementUpdateEnabled","NEVER","AUTO","wallets","applePay","googlePay","_getStripeElementTerms","_updateStripeLinkStateByElementType","_updateStripeElement","_confirmStripePaymentOrThrow","stripePaymentData","confirmPayment","confirmationResult","shouldShowTerms","terms","paymentElementType","isStripeLinkElementType","Link","stripeScriptLoader","stripeSVGSizeCoefficient","_initializeStripeElement","paymentMethodSelect","handleClosePaymentMethod","_getElementAppearance","fonts","cssSrc","defaultCollapsed","radios","spacedAccordionItems","visibleAccordionItemsCount","_onStripeElementChange","_collapseStripeElement","titleFontSize","titleFontWeight","titleColor","radioFocusColor","radioIconOuterWidth","radioIconOuterStrokeWidth","radioIconInnerWidth","radioIconSize","_getRadioIconSizes","borderBottomWidth","outerWidth","strokeWidth","outerStrokeWidth","stroke","innerRadius","fill","realOuterWidth","realOuterStrokeWidth","realInnerWidth","percentageCoefficient","innerWidth","stripeEqualOuterWidth","stripeEqualOuterStrokeWidth","stripeEqualInnerRadius","collapse","payment_method_id","selectedMethodId","isStripePaymentEvent","collapsed","FieldType","tdOnlineMartScriptLoader","tdInputs","CARD_NUMBER","CVV","EXPIRY","loadTDOnlineMartJs","tdOnlineMartClient","mountHostedFields","getPaymentPayloadOrThrow","processWithAdditionalAction","inputElement","commonPaymentData","digitalItemsInCart","shouldAddVerificationToken","isTrustedVaultingInstrument","getTokenOrThrow","throwTokenizationError","getHostedFieldsOptions","getTDOnlineMartClientOrThrow","inputId","isCreateTokenError","tdOnlineMartWindow","customcheckout","PAYMENT_CANNOT_CONTINUE","worldpay","_submitAdditionalAction","iframeHidden","_isValidJsonWithSessionId","SessionId","onLoadError","_createHiddenIframe","formId","inputBin","inputJWT","userAgent","match","srcdoc","outerHTML","str","saveExternalId","externalId","storefrontPaymentRequestSender","_prepareForReferredRegistration","CountryActionType","_countryRequestSender","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","createPaymentStrategyRegistry","paymentStrategyFactories","createPaymentStrategy","PaymentStrategyType","NO_PAYMENT_DATA_REQUIRED","FinalizeRequested","_loadOrderPaymentsIfNeeded","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","_namespace","isPPSDKPaymentMethod","initializationStrategy","PPSDK","_getToken","KLARNAV2","_hasFactoryForMethod","OFFLINE","isBraintreeFormFieldsMap","isBraintreeHostedFormError","invalidFieldKeys","BraintreeHostedFormType","_isInitializedHostedForm","_formOptions","_mapFieldType","_mapErrors","_handleCardTypeChange","cards","_handleInputSubmitRequest","_handleValidityChange","_isValidForm","_mapValidationErrors","StoredCardVerification","_mapFieldOptions","_mapStyleOptions","_cardFields","braintreeHostedFormState","_mapBillingAddress","tokenizationPayload","_mapTokenizeError","tokenizeForStoredCardVerification","countryName","internalLabel","expirationDate","cvv","mapStyles","_isValidParam","isPotentiallyValid","fieldKey","_createInvalidError","isStoredCard","cvvValidation","_createRequiredError","expirationDateValidation","cardNumberValidation","cardNameValidation","formErrorDataKey","_braintreeHostedForm","_threeDSecureOptions","preloadPaypalCheckout","tokenizeCard","_getErrorsRequiredFields","_mapToCreditCard","creditCards","challenge3DSVerification","appendSessionId","processedPayment","initializeHostedForm","validateHostedForm","isInitializedHostedForm","deinitializeHostedForm","tokenizeHostedForm","tokenizeHostedFormForStoredCardVerification","verifyCardWithHostedForm","_present3DSChallenge","addFrame","removeFrame","challengeRequested","additionalInformation","cancelVerifyCard","verification","roundedAmount","collectDeviceData","endpoint","_braintreePaymentProcessor","_braintreeIntegrationService","_isHostedFormInitialized","_is3dsEnabled","_deviceSessionId","_shouldInitializeBraintreeFastlane","_initializeBraintreeFastlaneOrThrow","_prepareHostedPaymentData","_preparePaymentData","_isSubmittingWithStoredCard","_shouldPerform3DSVerification","storedCreditCardNonce","_initializeBraintreeVenmo","_braintreeVenmoCheckout","_formattedPayload","_braintreeVenmoTokenize","_paymentStrategyActionCreator","visaInitOptions","isCreditCardLike","_CBAMGPSScriptLoader","_sessionId","isTestModeFlagEnabled","_threeDSjs","isConfigured","wsVersion","storeId","_initiateAuthentication","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","_authenticatePayer","attempt","authenticatePayer","cause","fullScreenRedirect","ThreeDS","_masterpassClient","_walletButton","_createMasterpassPayload","ActionTypes","isOpyPaymentMethod","widgetConfig","OpyErrorType","InvalidCart","_storefrontPaymentRequestSender","opy","_installWidget","nextAction","FORM_POST","formPost","formPostUrl","formFields","fieldName","fieldValue","append","decodeURI","widgetContainer","loadOpyWidget","Config","OpyRegion","AU_REGION_URL","SOURCES","AU","UK","US","OpenpayWidgets","_useRedirectFlow","paypalexpress","useRedirectFlow","_isInContextEnabled","_paypalSdk","closeFlow","_isAcknowledgedOrFinalized","initXO","startFlow","SubStrategyType","PENDING_REDIRECT_PARAM","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","stringifyUrl","exclude","isAnyContinue","overSome","x","isString","isUndefined","availableMethods","_humanVerificationHandler","form_fields","redirectionState","RedirectionState","handleRedirect","humanVerificationHandler","available_methods","handleHumanVerification","humanVerification","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","isError","createStepHandler","StepHandler","ContinueHandler","COMPLETED_PAYMENTS_KEY","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","_subStrategyRegistry","_paymentResumer","_completedPayments","PPSDKCompletedPayments","subStrategy","resume","getPPSDKMethod","_subStrategy","getToken","cond","constant","CARD","NONE","stubTrue","UNSUPPORTED","_ppsdkStepHandler","humanVerificationCallback","_stepHandler","createSubStrategyRegistry","stepHandler","SubStrategyRegistry","CardSubStrategy","NoneSubStrategy","auth_token","_wepayRiskClient","getRiskToken","payloadWithToken","_riskClient","WePay","risk","generate_risk_token","get_risk_token","InstrumentActionType","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","session","_getSessionContext","_getCurrentAccessToken","_getShippingAddress","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","valueOf","isFuture","vaultAccessExpiry","newDate","getTime","setMinutes","getMinutes","getVaultAccessToken","isTransactional","transformResponse","vaultedInstruments","_transformVaultedInstruments","vaulted_instruments","transformErrorResponse","transformVaultAccessResponse","expires_at","_isPayPalInstrument","default_instrument","external_id","trusted_shipping_address","mapToPayPalInstrument","_isBankInstrument","mapToBankInstrument","last_4","untrusted_shipping_address_card_verification_mode","mapToCardInstrument","method_type","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionType","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","getConsignmentById","consignmentLineItems","cartItems","searchArea","ShippingStrategyActionType","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","_amazonPayV2PaymentProcessor","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","onPayPalFastlaneAddressChange","_shouldRunAuthenticationFlow","_runAuthenticationFlowOrThrow","_shouldUseBraintreeFastlaneShippingComponent","_handleBraintreeFastlaneShippingAddressChange","_getPayPalBillingAddress","paypalPhoneNumber","_mapPayPalToBcAddress","_mergeShippingAndBillingAddresses","_mapPayPalToBcInstrument","_getCountryNameByCountryCode","_normalizeAddress","showShippingAddressSelector","selectedAddress","paymentProviderCustomerAddresses","_filterAddresses","_isEqualAddresses","_getBraintreePaymentMethodOrThrow","isFastlaneEnabled","_paypalCommerceSdk","_paypalCommerceFastlaneUtils","_shouldAuthenticateUserWithFastlane","_initializePayPalSdk","_authenticateUserWithFastlaneOtp","_shouldUsePayPalFastlaneShippingComponent","_handlePayPalShippingAddressChange","_getPayPalPaymentMethodOrThrow","_getPayPalCustomerAuthenticationState","paypalConnectSessionId","customerAuthenticationState","billingAddressEmail","_stripeUPEScriptLoader","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionType","sendSignInEmail","emailRequest","SendSignInEmailRequested","SendSignInEmailSucceeded","SendSignInEmailFailed","_messageCustomizer","_extensionEventBroadcaster","_countryActionCreator","_couponActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_pickupOptionActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","isDevelopment","_errorTransformer","isCheckoutServiceError","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","loadPaymentMethodByIds","deinitializePayment","loadBillingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","handleExtensionCommand","handler","CheckoutService","withMemoizedCombiner","creator","combiner","pop","combinerArgs","createSelectorCreator","defaultMemoize","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","currentValue","newValue","objectSet","DEFAULT_STATE","statuses","billingAddressReducer","combineReducers","dataReducer","composeReducers","errorsReducer","statusesReducer","reducer","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","objectMerge","currentObject","newObject","CheckoutButtonActionType","cartReducer","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","configReducer","couponReducer","giftCertificateReducer","customerReducer","customerStrategyReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isInitializing","isDeinitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","extensionReducer","formFieldsReducer","countryReducer","orderReducer","metaReducer","orderBillingAddressReducer","paymentReducer","paymentMethodReducer","array","defaultPredicate","derivedPredicate","findIndex","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","isLoadingMethod","paymentStrategyReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","isExecuting","isFinalizing","paymentProviderCustomerReducer","instrumentReducer","deleteError","failedInstrument","isDeleting","deletingInstrument","remoteCheckoutReducer","updateShippingOptionError","updateError","isUpdating","isUpdatingShippingOption","consignmentReducer","objectFlatten","parent","flattened","keyString","objectWithSortedKeys","sortedArray","current","pickupOptionReducer","sortedflattenedMeta","shippingCountryReducer","shippingStrategyReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","isUpdatingAddress","isSelectingOption","signInEmailReducer","storeCreditReducer","subscriptionsReducer","checkoutReducer","createFreezeProxy","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","deepFreeze","trap","createProxy","barclays","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","moneris","cba_mpgs","worldpayaccess","tdonlinemart","normalize","createInternalCheckoutSelectorsFactory","getUpdateError","getContinueAsGuestError","getLoadError","isContinuingAsGuest","getInitializeError","getDeinitializeError","getCoupons","getRemoveError","getApplyError","isApplying","isRemoving","getCreateAccountError","isCreatingCustomerAccount","getCreateAddressError","isCreatingCustomerAddress","getOrderBillingAddress","getInternalPayment","getGatewayPayment","getHostedPayment","isPaymentDataSubmitted","getEmail","getSendError","isSending","createBillingAddressSelector","continueAsGuestError","loadError","memoizeOne","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","createConfigSelector","getFlashMessages","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","removeCouponError","applyCouponError","isApplyingCoupon","isRemovingCoupon","createCustomerSelector","isCreating","createAddressError","isCreatingAddress","createCustomerStrategySelector","getSignInError","getSignOutError","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","getGiftCertificates","removeGiftCertificateError","applyGiftCertificateError","isApplyingGiftCertificate","isRemovingGiftCertificate","createGiftCertificateSelectorFactory","createInstrumentSelector","getInstrumentsByPaymentMethod","paymentMethodKey","currentMethod","isMatch","supportedProvider","getDeleteError","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","getBillingAddressFields","getCustomerAccountFields","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","getPaymentMethods","getLoadMethodError","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getExecuteError","getFinalizeError","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","getPickupOptions","pickupOptions","sortedFlattenedParams","createPickupOptionSelectorFactory","createPaymentProviderCustomerSelector","createRemoteCheckoutSelector","createShippingAddressSelector","shippingConsignment","shippingConsignments","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","getUpdateAddressError","getSelectOptionError","createShippingStrategySelectorFactory","createConsignmentSelector","addressA","addressB","getCreateError","getLoadShippingOptionsError","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","getUpdateShippingOptionError","isLoadingShippingOptions","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","isExecutingSpamCheck","createCheckoutSelectorFactory","createOrderSelector","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createPaymentSelector","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","signInEmail","sendError","createExtensionSelector","createExtensionSelectorFactory","checkoutButton","orderBillingAddress","remoteCheckout","shippingCountries","selectors","shouldWarnMutation","createCheckoutStore","initialState","requestErrorFactory","actionTransformer","action$","createInternalCheckoutSelectors","createCheckoutService","getShippingOptions","getSelectedShippingOption","getBillingCountries","getSelectedPaymentMethod","getSignInEmail","getUserExperienceSettings","getSelectShippingOptionError","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","createCheckoutStoreSelector","createCheckoutStoreErrorSelector","createCheckoutStoreStatusSelector","checkoutVariantIdentificationToken","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","customerRegistryV2","extensionActionCreator","ExtensionActionCreator","ExtensionRequestSender","extensionMessenger","ExtensionMessenger","storeProjection","val","checkoutUserExperienceSettings","getLoadCheckoutError","getUpdateCheckoutError","getSubmitOrderError","getFinalizeOrderError","getLoadOrderError","getLoadCartError","getLoadBillingCountriesError","getLoadShippingCountriesError","getLoadPaymentMethodsError","getLoadPaymentMethodError","getInitializePaymentError","getInitializeCustomerError","getUpdateBillingAddressError","getUpdateSubscriptionsError","getUpdateShippingAddressError","getDeleteConsignmentError","getUpdateConsignmentError","getCreateConsignmentsError","getInitializeShippingError","getApplyStoreCreditError","getApplyCouponError","getRemoveCouponError","getApplyGiftCertificateError","getRemoveGiftCertificateError","getLoadInstrumentsError","getDeleteInstrumentError","getLoadConfigError","getSignInEmailError","getCreateCustomerAccountError","getCreateCustomerAddressError","getPickupOptionsError","getLoadExtensionsError","isLoadingCheckout","isUpdatingCheckout","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isUpdatingBillingAddress","isUpdatingSubscriptions","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isCreatingConsignments","isInitializingShipping","isApplyingStoreCredit","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isLoadingPickupOptions","messenger","subscribers","ExtensionEventBroadcaster","createExtensionEventBroadcaster","remoteCheckoutRequestSender","paymentRequestTransformer","paymentRequestSender","braintreePaymentProcessor","braintreeHostedForm","createBraintreePaymentProcessor","paymentStrategyActionCreator","BARCLAYS","BRAINTREE_VISA_CHECKOUT","CBA_MPGS","CONVERGE","BNZ","MASTERPASS","OPY","PAYPAL_EXPRESS","PAYPAL_EXPRESS_CREDIT","PPSDKStrategy","PaymentResumer","WE_PAY","consignmentRequestSender","createShippingStrategyRegistry","isTerminalCacheKeyMap","_lastId","_map","maps","_usedMaps","maxSize","onExpire","getKey","_resolveMap","parentMap","usedCount","_generateMap","_removeLeastUsedMap","getUsedCount","isMatched","mapIndex","unshift","terminalMap","recentlyUsedMap","_removeMap","isRootCacheKeyMap","selectorDecorator","resolver","memoizedMethod","cachedValue","isPrivate","selectorMethodDecorator","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","CheckoutButtonErrorSelector","isInitializingButton","isDeinitializingButton","CheckoutButtonStatusSelector","createCheckoutButtonSelectors","_buttonStrategyActionCreator","_state","initializeButton","containerIds","idPrefix","containers","uniqueId","setUniqueElementId","deinitializeButton","CheckoutButtonInitializer","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","fundingicons","tagline","messagingContainerId","_renderPayPalComponents","_renderPayPalMessages","_renderPayPalButton","shouldProcessPayment","onAuthorizeError","onEligibilityFailure","validButtonStyle","_setupPayment","_tokenizePayment","_removeElement","isMessageContainerAvailable","_createBuyNowCart","_buyNowCart","buyNowCartId","CheckoutButtonNotInitialized","_paypalScriptLoader","_host","fundingCreditOption","allowedSources","allowCredit","disallowedSources","Button","funding","allowed","disallowed","RECT","RESPONSIVE","onAuthorize","paymentID","payerID","payerId","payerInfo","payer_info","isWithBuyNowFeatures","amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","_buyNowInitializeOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCartOrThrow","_createCheckoutConfig","public_key","rest","payloadJSON","buyNowCart","amazonPayV2RequestSender","ButtonStyleOption","_requiresShipping","defaultStyle","backgroundPosition","backgroundRepeat","backgroundSize","cursor","minHeight","minWidth","White","backgroundImage","WhiteBorder","Black","getApplePayButtonStyle","_getRequestWithEmptyTotal","onpaymentmethodselected","_handlePaymentMethodSelected","completePaymentMethodSelection","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","domainUrl","buttonHeight","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","paymentSuccess","toVisaCheckoutAddress","alignItems","getVenmoButtonStyle","WHITE","BLUE","braintreevenmo","cartButtonStyles","renderVenmoButton","handleInitializationVenmoError","removeVenmoContainer","venmoButton","buyBowCart","removeAttribute","handlePostForm","_getMethodOrThrow","_countryCode","_getBuyNowTransactionInfo","_getTransactionInfo","buyNowFlowCallbacks","messagingContainer","paypalMessagesSdk","getValidVenmoButtonStyles","gold","paypalExpressScriptLoader","loadPaypalSDK","paypalSDK","getStyle","getPaymentData","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","braintreeSdkCreator","BRAINTREE_PAYPAL_CREDIT","PAYPALEXPRESS","createCheckoutButtonRegistry","EmbeddedCheckoutEventType","NotEmbeddableErrorType","UnknownError","EmbeddedContentEventType","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","_iframeCreator","_messageListener","_messagePoster","_loadingIndicator","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","encodeURIComponent","lastAttempt","MissingContent","EmbeddedCheckout","MissingContainer","allowPaymentRequest","allow","contentId","STORAGE_PREFIX","embedCheckout","handleFrameLoadedEvent","hasAttribute","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","_notifyMessageHandlers","IframeEmbeddedCheckoutMessenger","NoopEmbeddedCheckoutMessenger","createEmbeddedCheckoutMessenger","parentWindow","DEFAULT_LOCALE","KEY_PREFIX","_logger","_transformConfig","locales","_locales","_translations","_formatters","_isCspNonceExperimentEnabled","isCspNonceExperimentEnabled","mapKeys","translationKey","_hasTranslations","translate","prefixedKey","IntlMessageFormat","_escapeSpecialCharacters","ignoreTag","_transformData","_isFormatError","originalMessage","messageFormat","compile","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","union","fallbackLocale","parentKey","resultKey","LanguageService","createLanguageService","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","checkoutService","analytics","checkoutSteps","_checkoutStarted","_completedSteps","_viewedSteps","_analyticStepOrder","trackCheckoutStarted","extraItemsData","track","getTrackingPayload","revenue","trackOrderComplete","isMissingOrdersExperimentEnabled","affiliation","products","product","trackStepViewed","stepId","getIdFromStep","hasStepViewed","trackViewed","backfill","trackStepCompleted","hasStepCompleted","trackCompleted","shippingMethod","getShopperCurrency","getPaymentMethodName","shipping_method","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","physicalAndDigitalItems","itemAttributes","image_url","createStepTracker","stepTrackerConfig","isBraintreeFastlaneWindow","_selectedPaymentMethodId","customerPaymentMethodExecuted","_shouldTrackFastlaneEvent","_trackEmailSubmitted","paymentComplete","_trackOrderPlaced","selectedPaymentMethod","_trackApmSelected","walletButtonClick","isAnalyticEnabled","isBraintreeAnalyticsV2Enabled","isAvailableAnalyticEventsMethods","events","_getBraintreeEventsOrThrow","emailSubmitted","_getEmailSubmittedEventOptions","isWalletButton","apmSelected","_getApmSelectedEventOptions","orderPlaced","_getOrderPlacedEventOptions","_getEventCommonOptions","isGuestCustomer","experiments","treatment_group","context_type","context_id","page_type","page_name","partner_name","user_type","store_id","merchant_name","experiment","apmList","user_email_saved","apm_shown","apm_list","apm_selected","apm_location","selected_payment_method","currency_code","createBraintreeAnalyticTracker","_checkoutService","paypalHostWindow","_getPayPalEventsOrThrow","createPayPalCommerceAnalyticTracker","createStoredCardHostedFormService","AnalyticStepType","AnalyticStepOrder","bodlEvents","_emailEntryBegan","_shippingOptionsShown","setState","checkoutBegin","_getCommonCheckoutData","emitCheckoutBeginEvent","orderPurchased","emitOrderPurchasedEvent","event_id","channel_id","cart_value","coupon_codes","shipping_cost","line_items","_getProducts","stepCompleted","currentStep","_hasStepCompleted","_trackCompletedStep","customerEmailEntry","emit","customerSuggestionInit","customerSuggestionExecute","showShippingMethods","paymentOption","commonData","emitPaymentDetailsProvidedEvent","clickPayButton","paymentRejected","exitCheckout","_trackShippingStepCompleted","emitShippingDetailsProvidedEvent","base_price","sale_price","purchase_price","product_name","gift_certificate_id","gift_certificate_name","gift_certificate_theme","theme","variant_id","coupon_amount","couponAmount","brand_name","category_names","flatten","retail_price","retailPrice","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/checkout-sdk.umd.js b/dist/checkout-sdk.umd.js index 16df864fc7..b53a2811e7 100644 --- a/dist/checkout-sdk.umd.js +++ b/dist/checkout-sdk.umd.js @@ -1,3 +1,3 @@ /*! For license information please see checkout-sdk.umd.js.LICENSE.txt */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.checkoutKit=e():t.checkoutKit=e()}(self,(()=>(()=>{var t={22723:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(95757)),i=l(n(61461)),a=l(n(20501)),s=l(n(22682)),u=l(n(33697)),c=l(n(98610));function l(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function p(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,e.default={host:""}},88604:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},55739:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(88604),o=n(40816),i={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:o.GET};e.default=i},40816:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},71249:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(88477),n(14718),n(57188),n(62342),n(25226),n(13521),n(35157),n(25766),n(53618),n(11062),n(948),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=(o=n(95757))&&o.__esModule?o:{default:o},a=n(88604),s=n(30390);function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,s.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,o=t.statusText,i="response"in t?t.response:t.responseText;return i&&(0,s.includes)(n,a.APPLICATION_JSON)&&(i=JSON.parse(i)),{data:i,headers:e,status:r,statusText:o}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,i.default)({},t,function(t,e,n){return(e=l(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&c(e.prototype,n),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},24475:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=l(n(65778)),i=l(n(95757)),a=n(40816),s=l(n(55739)),u=l(n(71249)),c=l(n(24475));function l(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function p(t,e){for(var n=0;n=200&&t.status<300}}])&&p(e.prototype,n),r&&p(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}()},36421:(t,e,n)=>{"use strict";n(47818),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},30390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return d.default}});var r=p(n(36421)),o=p(n(40570)),i=p(n(67522)),a=p(n(67150)),s=p(n(59731)),u=p(n(41207)),c=p(n(29503)),l=p(n(50377)),d=p(n(31887));function p(t){return t&&t.__esModule?t:{default:t}}},45212:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},46885:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,o.default)(t)};var r=i(n(45212)),o=i(n(40570));function i(t){return t&&t.__esModule?t:{default:t}}},40570:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},67522:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===o(t)&&!Array.isArray(t)}},67150:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(46885)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},59731:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t,r.default)};var r=i(n(40570)),o=i(n(41207));function i(t){return t&&t.__esModule?t:{default:t}}},41207:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,o.default)(t)?Object.keys(t).reduce((function(n,r){var o=t[r];return e(o)||(n[r]=o),n}),{}):t};var r,o=(r=n(67522))&&r.__esModule?r:{default:r}},29503:(t,e,n)=>{"use strict";n(8933),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},50377:(t,e,n)=>{"use strict";n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},31887:(t,e,n)=>{"use strict";n(25226),n(69204),n(13521),n(88315),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},34936:(t,e,n)=>{"use strict";e.U=function(t){return o.default.create(t)};var r,o=(r=n(22723))&&r.__esModule?r:{default:r}},22682:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=s(n(84916)),i=s(n(39835)),a=s(n(76473));function s(t){return t&&t.__esModule?t:{default:t}}function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(74152),i=n(92299),a=u(n(87730)),s=u(n(76473));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e,n){return(e=u(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=d(n(95757)),i=n(30390),a=d(n(77140)),s=d(n(84094)),u=d(n(65245)),c=d(n(69465)),l=d(n(27231));function d(t){return t&&t.__esModule?t:{default:t}}function p(t){return p="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},p(t)}function f(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE_ACCELERATED_CHECKOUT=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.BRAINTREE_ACCELERATED_CHECKOUT="braintreeacceleratedcheckout",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ACCELERATED_CHECKOUT="paypalcommerceacceleratedcheckout",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},69465:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(6073),i=n(34526);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function s(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},20501:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=c(n(84916)),i=n(92299),a=c(n(18581)),s=c(n(46833)),u=c(n(76473));function c(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function d(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},46833:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=n(6073);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=c(n(64003)),a=c(n(85195)),s=c(n(67093)),u=c(n(16620));function c(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=s(n(95757)),i=n(30390),a=s(n(69465));function s(t){return t&&t.__esModule?t:{default:t}}function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(88315),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(80404),n(62342),n(18864),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390),i=c(n(72052)),a=c(n(33018)),s=c(n(88124)),u=c(n(86883));function c(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o,i=n(30390),a=(o=n(69465))&&o.__esModule?o:{default:o};function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=n(30390);function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(11138),n(14718),n(62342),n(25226),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var o=u(n(84916)),i=n(40816),a=u(n(93684)),s=n(91486);function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function i(t,e){for(var n=0;n{"use strict";n(80404),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,i,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=a.providerName,u=a.defaultInstrument,c=(0,r.omitNil)({name:s});return(0,r.omitNil)({provider:c,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,i=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:i})),billing_address:o(a.billingAddress),default_instrument:u})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return o(t)}))}):(0,r.omitNil)({shipping_address:o(t.shippingAddress)})};var r=n(30390);function o(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:o})}},2467:(t,e,n)=>{"use strict";n(21894),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function(t,e){var n=(e||{}).equalityCheck,i=void 0===n?o:n;return function(e,n){return Object.keys(t).reduce((function(o,a){var s,u=t[a],c=e?e[a]:void 0,l=u(c,n);return i(c,l)&&o?o:r.assign({},o,((s={})[a]=l,s))}),e||{})}}},19492:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(44396),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(96150);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(45550);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},o.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},69199:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2467),o=n(56498);e.default=function(t,e,n){return"function"==typeof t?new o.default(t,e,n):new o.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},69776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(83736),o=n(49997);e.default=function(t,e,n){return r.__assign({},o.default(t,e,n),{error:!0})}},56498:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14266),n(14718),n(80404),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var o=n(83736),i=n(45550),a=n(87218),s=n(57532),u=n(96150),c=n(45926),l=n(2557),d=n(12079),p=n(64472),f=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=o.__assign({actionTransformer:d.default,equalityCheck:u,shouldWarnMutation:!0,stateTransformer:p.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(s.mergeMap((function(t){return t.pipe(s.concatMap((function(t){return t})))})),s.filter((function(t){return!!t.type})),s.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),s.distinctUntilChanged((function(t,e){var n=t.state,o=e.state;return r._options.equalityCheck(n,o)})),s.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return l.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],o=1;o0&&(u=u.pipe(s.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),i&&!1===i.initial&&(u=u.pipe(s.skip(1)));var c=[u.subscribe(t),this._notification$.subscribe(t)];return function(){return c.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):c.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,o){var u=n._getDispatchError(e.queueId),c=n._options.actionTransformer(a.from(t).pipe(s.map((function(t){return e.queueId?i.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(c).pipe(s.map((function(t,e){return 0===e&&u.pipe(s.first()).subscribe(o),t.error&&o(t.payload),t})),s.catchError((function(t){return o(t instanceof Error?t:t.payload),a.of(t)})),s.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=f},45926:(t,e,n)=>{"use strict";n(80404),n(56949),n(32194),n(38085),Object.defineProperty(e,"__esModule",{value:!0});var r=n(45550),o=n(96150);e.default=function t(e,n){try{var i=n||{},a=i.equalityCheck,s=void 0===a?o:a,u=i.previousValue,c=void 0===u?null:u;return s(e,c)&&Object.isFrozen(c)?c:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:s,previousValue:Array.isArray(c)?c[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:s,previousValue:c&&c.hasOwnProperty(r)?c[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},99840:(t,e,n)=>{"use strict";n(56498).default;var r=n(2467);e.HY=r.default;var o=n(19492);e.om=o.default;var i=n(49997);e.VP=i.default;var a=n(69199);e.iN=a.default;var s=n(69776);e.fQ=s.default;var u=n(45926);e.ol=u.default},2557:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},12079:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},64472:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},83736:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>_,__asyncGenerator:()=>w,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>d,__classPrivateFieldGet:()=>E,__classPrivateFieldSet:()=>O,__createBinding:()=>f,__decorate:()=>u,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>P,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>c,__read:()=>m,__rest:()=>s,__spread:()=>v,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;u--)(i=t[u])&&(s=(a<3?i(s):a>3?i(e,n,s):i(e,n))||s);return a>3&&s&&Object.defineProperty(e,n,s),s}function c(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function d(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}u((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function v(){for(var t=[],e=0;e1||s(t,e)}))})}function s(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(u,c):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function u(t){s("next",t)}function c(t){s("throw",t)}function l(t,e){t(e),i.shift(),i.length&&s(i[0][0],i[0][1])}}function _(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function P(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function E(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function O(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},21887:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(60834),o=n(33788);e.default=function(t){var e=new r.default;return new o.default(e,t)}},60834:(t,e,n)=>{"use strict";n(21894),n(44594),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,o=document.createElement("form");return o.style.display="none",o.setAttribute("action",t),o.setAttribute("method","POST"),o.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];o.appendChild(r._createInput(n,t))})),o},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},33788:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(12789),o=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var o=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(o),o.submit()},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!(0,r.isAbsoluteUrl)(t)?(0,r.joinPaths)(this._options.host,t):t},t}();e.default=o},74152:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FormPoster=e.createFormPoster=void 0;var r=n(21887);Object.defineProperty(e,"createFormPoster",{enumerable:!0,get:function(){return r.default}});var o=n(33788);Object.defineProperty(e,"FormPoster",{enumerable:!0,get:function(){return o.default}})},12789:(t,e,n)=>{"use strict";n(98556),n(53618),Object.defineProperty(e,"__esModule",{value:!0}),e.joinPaths=e.isAbsoluteUrl=void 0,e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return"".concat((n=t,n.replace(/\/$/,"")),"/").concat(function(t){return t.replace(/^\//,"")}(e));var n}},89998:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},26879:(t,e,n)=>{"use strict";n(47818),n(80404),n(44396),n(67068),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=n(45550),i=r.__importDefault(n(96150)),a=n(89998),s=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:i.default,maxSize:0,onExpire:o.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(71652);e.Bj=r.default,e.B4=r.memoizeOne},71652:(t,e,n)=>{"use strict";n(14718),n(20363),n(13521),n(25766),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=n(188),o=r.__importDefault(n(59745)),i=r.__importDefault(n(96150)),a=r.__importDefault(n(26879));function s(t,e){var n=r.__assign({maxSize:0,isEqual:i.default},e),s=n.maxSize,u=n.isEqual,c=new Map,l=new a.default({isEqual:u,maxSize:s,onExpire:function(t){return c.delete(t)}}),d=o.default(t,(function(){for(var t=[],e=0;e{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>_,__asyncGenerator:()=>w,__asyncValues:()=>S,__await:()=>b,__awaiter:()=>d,__classPrivateFieldGet:()=>E,__classPrivateFieldSet:()=>O,__createBinding:()=>f,__decorate:()=>u,__exportStar:()=>h,__extends:()=>i,__generator:()=>p,__importDefault:()=>I,__importStar:()=>P,__makeTemplateObject:()=>C,__metadata:()=>l,__param:()=>c,__read:()=>m,__rest:()=>s,__spread:()=>v,__spreadArrays:()=>g,__values:()=>y}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o(t,e)};function i(t,e){function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;u--)(i=t[u])&&(s=(a<3?i(s):a>3?i(e,n,s):i(e,n))||s);return a>3&&s&&Object.defineProperty(e,n,s),s}function c(t,e){return function(n,r){e(n,r,t)}}function l(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function d(t,e,n,r){return new(n||(n=Promise))((function(o,i){function a(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}u((r=r.apply(t,e||[])).next())}))}function p(t,e){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function v(){for(var t=[],e=0;e1||s(t,e)}))})}function s(t,e){try{(n=o[t](e)).value instanceof b?Promise.resolve(n.value.v).then(u,c):l(i[0][2],n)}catch(t){l(i[0][3],t)}var n}function u(t){s("next",t)}function c(t){s("throw",t)}function l(t,e){t(e),i.shift(),i.length&&s(i[0][0],i[0][1])}}function _(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,o){e[r]=t[r]?function(e){return(n=!n)?{value:b(t[r](e)),done:"return"===r}:o?o(e):e}:o}}function S(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,o){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,o,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function P(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function E(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function O(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},78163:(t,e,n)=>{"use strict";n.d(e,{g:()=>o}),n(21894);var r=n(43419),o=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.As(e)},t}()},60931:(t,e,n)=>{"use strict";n.d(e,{A:()=>s});var r=n(77650),o=n(39649),i=n(30187),a=n(71844);function s(t){return new a.A(new i.A,new o.A,r,t)}},33767:(t,e,n)=>{"use strict";n.d(e,{A:()=>o});var r=n(85466);function o(t){return new r.A(t)}},9285:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>i.A,Timeout:()=>a.A,createRequestSender:()=>r.A,createTimeout:()=>o.A});var r=n(60931),o=n(33767),i=n(71844),a=n(85466)},66029:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(92947)},39649:(t,e,n)=>{"use strict";n.d(e,{A:()=>s}),n(57188),n(53618),n(11062),n(948);var r=n(31355),o=n(38780),i=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const s=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(i.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,o.A)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&i.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,o=e.split(":"),i=(o.shift()||"").trim();return i?(0,r.Cl)((0,r.Cl)({},t),((n={})[i.toLowerCase()]=o.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},30187:(t,e,n)=>{"use strict";n.d(e,{A:()=>o}),n(14266),n(21894),n(44594);var r=n(43419);const o=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.As(e,{encode:n}):t},t}()},71844:(t,e,n)=>{"use strict";n.d(e,{A:()=>c}),n(13521),n(67536),n(84090),n(88315),n(95743),n(53618),n(11062);var r=n(31355),o=n(40117),i=n.n(o),a=n(78163),s=n(66029),u=n(85466);const c=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.g}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),o=this._getCachedRequest(t,r);if(o)return Promise.resolve(o);var i=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,o){var a=function(){var a=n._payloadTransformer.toResponse(i);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):o(a)};i.onload=a,i.onerror=a,i.onabort=a,i.ontimeout=a,r.timeout instanceof u.A&&(r.timeout.onComplete((function(){return i.abort()})),r.timeout.start()),(0,s.A)(r.timeout)&&r.timeout.then((function(){return i.abort()})),i.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.Cl)((0,r.Cl)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&this._isLocalRequest(t)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),i()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t.prototype._isLocalRequest=function(t){return!!t.match(new RegExp("^(https?:)?//"+window.location.hostname))||!t.match(new RegExp("^(https?:)?//"))},t}()},85466:(t,e,n)=>{"use strict";n.d(e,{A:()=>r}),n(13521),n(67536);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},38780:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{A:()=>o}),n(91621),n(27481),n(90105),n(14266),n(14718),n(57188),n(80404),n(21894),n(13521),n(25766),n(92947)},43419:(t,e,n)=>{"use strict";n(91621),n(27481),n(90105),n(98556),n(14266),n(47818),n(14718),n(57188),n(80404),n(44396),n(18492),n(25226),n(21894),n(13521),n(25766),n(53618),n(11062),n(948),n(44594),n(92947);var r=n(23081),o=n(95757);n(88577);function i(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.As=function(t,e){!1===(e=o({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[i(e,t),"[",r,"]"].join(""):[i(e,t),"[",i(r,t),"]=",i(n,t)].join("")};case"bracket":return function(e,n){return null===n?i(e,t):[i(e,t),"[]=",i(n,t)].join("")};default:return function(e,n){return null===n?i(e,t):[i(e,t),"=",i(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var o=t[r];if(void 0===o)return"";if(null===o)return i(r,e);if(Array.isArray(o)){var a=[];return o.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return i(r,e)+"="+i(o,e)})).filter((function(t){return t.length>0})).join("&"):""}},31355:(t,e,n)=>{"use strict";n.d(e,{Cl:()=>r}),n(91621),n(27481),n(43366),n(90105),n(98556),n(47818),n(14718),n(90291),n(15277),n(68461),n(13521),n(67536),n(25766),n(92947);var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},50961:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(860);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},52904:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(9285),o=n(35707),i=n(79029);e.default=function(){return new i.default(new o.default,r.createRequestSender())}},54721:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(50961);e.default=function(){return r||(r=o.default()),r}},50808:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(52904);e.default=function(){return r||(r=o.default()),r}},4993:(t,e,n)=>{"use strict";n(860).default;var r=n(50961);e.Hb=r.default;var o=n(54721);e.vQ=o.default,n(79029).default,n(52904).default;var i=n(50808);e._U=i.default},860:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,o){var i=document.createElement("script"),a=e||{},s=a.async,u=void 0!==s&&s,c=a.attributes,l=void 0===c?{}:c;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onreadystatechange=function(){return r()},i.onerror=function(e){delete n._scripts[t],o(e)},i.async=u,i.src=t,document.body.appendChild(i)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var s=document.createElement("link");s.as="script",s.rel=a,s.href=t,s.onload=function(){r()},s.onerror=function(){delete n._preloadedScripts[t],o()},document.head.appendChild(s)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(o)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},79029:(t,e,n)=>{"use strict";n(14718),n(80404),n(21894),n(13521),n(67536),n(25766),n(44594),n(92947),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,o){var i=document.createElement("link"),a=e||{},s=a.prepend,u=void 0!==s&&s,c=a.attributes,l=void 0===c?{}:c;Object.keys(l).forEach((function(t){i.setAttribute(t,l[t])})),i.onload=function(){return r()},i.onerror=function(e){delete n._stylesheets[t],o(e)},i.rel="stylesheet",i.href=t,u&&document.head.children[0]?document.head.insertBefore(i,document.head.children[0]):document.head.appendChild(i)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,o){var i=(e||{}).prefetch,a=void 0!==i&&i,s=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(s)){var u=document.createElement("link");u.as="style",u.rel=a?"prefetch":"preload",u.href=t,u.onload=function(){r()},u.onerror=function(e){delete n._preloadedStylesheets[t],o(e)},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(o)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},36274:(t,e,n)=>{"use strict";e.Jt=void 0,n(66060),n(55652),n(42853),n(65853),n(76437),n(15314),n(92128),n(81847),n(7270),n(25834),n(25742),n(5882),n(89471),n(56967),n(21142),n(29348),n(77566),n(2521),n(293),n(52988),n(2375),n(79590),n(59596);var r=n(88020);e.Jt=r,n(90724)},59596:(t,e,n)=>{"use strict";var r=n(66060),o=n(55652),i=n(25742);t.exports=function(){return r()||o()||i()}},66060:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/Android/i.test(t)}},55652:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/CrOS/i.test(t)}},42853:(t,e,n)=>{"use strict";n(47818);var r=n(7270),o=n(2375),i=n(65853),a=n(52988),s=n(79590);t.exports=function(t){return!(-1===(t=t||window.navigator.userAgent).indexOf("Chrome")&&-1===t.indexOf("CriOS")||r(t)||o(t)||i(t)||a(t)||s(t))}},65853:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("DuckDuckGo/")}},7270:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Edge/")}},25834:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/Firefox/i.test(t)}},76437:(t,e,n)=>{"use strict";n(47818);var r=n(81847);t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE")||r(t)}},92128:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE 10")}},81847:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Trident/7")}},15314:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE 9")}},5882:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/FxiOS/i.test(t)}},89471:(t,e,n)=>{"use strict";var r=n(25742);t.exports=function(t){return t=t||window.navigator.userAgent,r(t)&&function(t){return/\bGSA\b/.test(t)}(t)}},56967:(t,e,n)=>{"use strict";n(47818);var r=n(25742),o=n(5882),i=/webkit/i;t.exports=function(t){return t=t||window.navigator.userAgent,r(t)&&function(t){return i.test(t)}(t)&&!function(t){return t.indexOf("CriOS")>-1}(t)&&!o(t)&&!function(t){return t.indexOf("FBAN")>-1}(t)}},21142:(t,e,n)=>{"use strict";var r=n(29348);t.exports=function(t,e){return e=void 0!==e?e:window.statusbar.visible,r(t)&&!e}},29348:(t,e,n)=>{"use strict";var r=n(25742),o=n(89471);t.exports=function(t){return t=t||window.navigator.userAgent,!!r(t)&&(!!o(t)||/.+AppleWebKit(?!.*Safari)/i.test(t))}},77566:(t,e,n)=>{"use strict";var r=n(29348);t.exports=function(t,e){return e=void 0!==e?e:window.statusbar.visible,r(t)&&e}},25742:(t,e,n)=>{"use strict";var r=n(2521);t.exports=function(t,e,n){void 0===e&&(e=!0),t=t||window.navigator.userAgent;var o=/iPhone|iPod|iPad/i.test(t);return e?o||r(t,n):o}},2521:t=>{"use strict";t.exports=function(t,e){return t=t||window.navigator.userAgent,e=e||window.document,/Mac|iPad/i.test(t)&&"ontouchend"in e}},293:(t,e,n)=>{"use strict";var r=n(5882),o=n(25834);t.exports=function(t){return t=t||window.navigator.userAgent,r(t)||/iPhone|iPod|iPad|Mobile|Tablet/i.test(t)&&o(t)}},52988:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("OPR/")||-1!==t.indexOf("Opera/")||-1!==t.indexOf("OPT/")}},2375:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/SamsungBrowser/i.test(t)}},79590:(t,e,n)=>{"use strict";n(47818),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Silk/")}},90724:(t,e,n)=>{"use strict";n(17186),n(95743);var r=n(42853);t.exports=function(t){return t=t||window.navigator.userAgent,!!window.PaymentRequest&&(!r(t)||function(t){var e=t.match(/Chrome\/(\d+)\./);return!!e&&parseInt(e[1],10)>=61}(t))}},88020:(t,e,n)=>{"use strict";n(47818),n(17186),n(95743);var r=n(66060),o=n(5882),i=n(29348),a=n(42853),s=n(2375),u=n(65853);function c(t){return(t=t||window.navigator.userAgent).indexOf("Opera Mini")>-1}t.exports=function(t){return t=t||window.navigator.userAgent,!(i(t)||o(t)||function(t){return t=t||window.navigator.userAgent,!!r(t)&&/Version\/[\d.]+/i.test(t)&&!c(t)&&!u(t)}(t)||c(t)||function(t){var e=(t=t||window.navigator.userAgent).match(/CriOS\/(\d+)\./);return!!e&&parseInt(e[1],10)<48}(t)||function(t){return!a(t)&&!s(t)&&/samsung/i.test(t)}(t))}},35647:(t,e,n)=>{"use strict";t.exports={number:n(71990),expirationDate:n(15862),expirationMonth:n(38138),expirationYear:n(62711),cvv:n(2999),postalCode:n(89333),creditCardType:n(30439)}},71990:(t,e,n)=>{"use strict";n(53618);var r=n(7759),o=n(30439);function i(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,s,u,c;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return i(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return i(null,!1,!1);if(0===(n=o(t)).length)return i(null,!1,!1);if(1!==n.length)return i(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return i(a,!1,!1);for(s=a.type===o.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),c=Math.max.apply(null,a.lengths),e.maxLength&&(c=Math.min(e.maxLength,c)),u=0;u{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},15862:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(14718),n(13521),n(25766),n(53618),n(92947);var o=n(15410),i=n(38138),a=n(62711);function s(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,u,c,l;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=o(t);else{if(null===t||"object"!==r(t))return s(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(u=i(n.month),c=a(n.year,e),u.isValid){if(c.isCurrentYear)return s(l=u.isValidForThisYear,l,n.month,n.year);if(c.isValid)return s(!0,!0,n.month,n.year)}return u.isPotentiallyValid&&c.isPotentiallyValid?s(!1,!0,null,null):s(!1,!1,null,null)}},38138:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(17186),n(53618),t.exports=function(t){var e,n,o=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=o)):r(!1,!1)}},62711:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}n(44396),n(25226),n(17186),n(53618),t.exports=function(t,e){var n,o,i,a,s;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(o=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===o?r(!1,t.slice(0,2)===String(n).slice(0,2)):o>4?r(!1,!1):(t=parseInt(t,10),i=Number(String(n).substr(2,2)),2===o?(s=i===t,a=t>=i&&t<=i+e):4===o&&(s=n===t,a=t>=n&&t<=n+e),r(a,a,s))):r(!1,!1)}},11476:(t,e,n)=>{"use strict";n(13521),n(88315),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},7759:(t,e,n)=>{"use strict";n(17186),t.exports=function(t){for(var e,n=0,r=!1,o=t.length-1;o>=0;)e=parseInt(t.charAt(o),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,o--;return n%10==0}},15410:(t,e,n)=>{"use strict";n(57188),n(5360),n(44396),n(25226),n(11062);var r=n(62711),o=n(11476);t.exports=function(t){var e,n,i,a,s;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),o(t)?{month:t[0]||"",year:t.slice(1).join()}:(i=t,n=0===(s=Number(i[0]))?2:s>1||1===s&&Number(i[1])>2?1:1===s?(a=i.substr(1),r(a).isPotentiallyValid?1:2):5===i.length?1:i.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},89333:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(47818),n(35823),n(44396),n(13521),n(88315),e.parse=function(t,e){if("string"!=typeof t)throw new TypeError("argument str must be a string");var n={},r=t.length;if(r<2)return n;var i=e&&e.decode||d,a=0,s=0,u=0;do{if(-1===(s=t.indexOf("=",a)))break;if(-1===(u=t.indexOf(";",a)))u=r;else if(s>u){a=t.lastIndexOf(";",s-1)+1;continue}var f=c(t,a,s),h=l(t,s,f),y=t.slice(f,h);if(!o.call(n,y)){var m=c(t,s+1,u),v=l(t,u,m);34===t.charCodeAt(m)&&34===t.charCodeAt(v-1)&&(m++,v--);var g=t.slice(m,v);n[y]=p(g,i)}a=u+1}while(an;){var r=t.charCodeAt(--e);if(32!==r&&9!==r)return e+1}return n}function d(t){return-1!==t.indexOf("%")?decodeURIComponent(t):t}function p(t,e){try{return e(t)}catch(e){return t}}},30439:(t,e,n)=>{"use strict";n(47818),n(80404),n(67068),n(21894),n(44594);var r,o=n(45237),i=n(97458),a=n(40179),s=n(84438),u=n(39187),c={},l={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},d=[l.VISA,l.MASTERCARD,l.AMERICAN_EXPRESS,l.DINERS_CLUB,l.DISCOVER,l.JCB,l.UNIONPAY,l.MAESTRO,l.ELO,l.MIR,l.HIPER,l.HIPERCARD];function p(t){return c[t]||o[t]}function f(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function h(t){var e,n=[];return s(t)?0===t.length?r.map((function(t){return i(p(t))})):(r.forEach((function(e){var r=p(e);u(t,r,n)})),(e=a(n))?[e]:n):[]}r=i(d),h.getTypeInfo=function(t){return i(p(t))},h.removeCard=function(t){var e=f(t);r.splice(e,1)},h.addCard=function(t){var e=f(t.type,!0);c[t.type]=t,-1===e&&r.push(t.type)},h.updateCard=function(t,e){var n,r=c[t]||o[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=i(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),c[n.type]=n},h.changeOrder=function(t,e){var n=f(t);r.splice(n,1),r.splice(e,0,t)},h.resetModifications=function(){r=i(d),c={}},h.types=l,t.exports=h},39187:(t,e,n)=>{"use strict";var r=n(97458),o=n(98834);t.exports=function(t,e,n){var i,a,s,u;for(i=0;i=s&&(u.matchStrength=s),n.push(u);break}}},45237:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},97458:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},40179:(t,e,n)=>{"use strict";n(14266),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},98834:(t,e,n)=>{"use strict";n(17186),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,o=t.substr(0,r),i=parseInt(o,10);return e=parseInt(String(e).substr(0,o.length),10),n=parseInt(String(n).substr(0,o.length),10),i>=e&&i<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},88577:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(98556),n(14718),n(57188),n(44396),n(21894),n(13521),n(84090),n(88315),n(25766),n(95743),n(53618),n(92947);var o="%[a-f0-9]{2}",i=new RegExp("("+o+")|([^%]+?)","gi"),a=new RegExp("("+o+")+","gi");function s(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],s(n),s(r))}function u(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(i)||[],n=1;n{"use strict";n(91621);var r=n(62034),o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(t,e,n){var i=e[n];if(null!=i){if(o.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");o.call(t,n)&&r(i)?t[n]=s(Object(t[n]),e[n]):t[n]=i}}function s(t,e){if(t===e)return t;for(var n in e=Object(e))o.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),s=0;s{"use strict";n(47818),n(21894),t.exports=function(t,e){for(var n={},r=Object.keys(t),o=Array.isArray(e),i=0;i{"use strict";t.exports=n(16809)},1676:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(91621),n(27481),n(90105),n(47818),n(14718),n(80404),n(44396),n(67068),n(25226),n(13521),n(17186),n(25766),n(11062),n(44594),n(92947),function(e){"use strict";if("undefined"!=typeof window){var n=!0,o=10,i="",a=0,s="",u=null,c="",l=!1,d={resize:1,click:1},p=128,f=!0,h=1,y="bodyOffset",m=y,v=!0,g="",b={},w=32,_=null,S=!1,C="[iFrameSizer]",P=C.length,I="",E={max:1,min:1,bodyScroll:1,documentElementScroll:1},O="child",A=!0,k=window.parent,T="*",x=0,M=!1,N=null,R=16,D=1,j="scroll",z=j,F=window,L=function(){ct("MessageCallback function not defined")},B=function(){},U=function(){},q={height:function(){return ct("Custom height calculation function not defined"),document.documentElement.offsetHeight},width:function(){return ct("Custom width calculation function not defined"),document.body.scrollWidth}},V={},H=!1;try{var G=Object.create({},{passive:{get:function(){H=!0}},once:{get:function(){}}});window.addEventListener("test",rt,G),window.removeEventListener("test",rt,G)}catch(t){}var W,Y,K,J,Q,Z,X,$=Date.now||function(){return(new Date).getTime()},tt={bodyOffset:function(){return document.body.offsetHeight+wt("marginTop")+wt("marginBottom")},offset:function(){return tt.bodyOffset()},bodyScroll:function(){return document.body.scrollHeight},custom:function(){return q.height()},documentElementOffset:function(){return document.documentElement.offsetHeight},documentElementScroll:function(){return document.documentElement.scrollHeight},max:function(){return Math.max.apply(null,St(tt))},min:function(){return Math.min.apply(null,St(tt))},grow:function(){return tt.max()},lowestElement:function(){return Math.max(tt.bodyOffset()||tt.documentElementOffset(),_t("bottom",Pt()))},taggedElement:function(){return Ct("bottom","data-iframe-height")}},et={bodyScroll:function(){return document.body.scrollWidth},bodyOffset:function(){return document.body.offsetWidth},custom:function(){return q.width()},documentElementScroll:function(){return document.documentElement.scrollWidth},documentElementOffset:function(){return document.documentElement.offsetWidth},scroll:function(){return Math.max(et.bodyScroll(),et.documentElementScroll())},max:function(){return Math.max.apply(null,St(et))},min:function(){return Math.min.apply(null,St(et))},rightMostElement:function(){return _t("right",Pt())},taggedElement:function(){return Ct("right","data-iframe-width")}},nt=(W=It,Q=null,Z=0,X=function(){Z=$(),Q=null,J=W.apply(Y,K),Q||(Y=K=null)},function(){var t=$();Z||(Z=t);var e=R-(t-Z);return Y=this,K=arguments,e<=0||e>R?(Q&&(clearTimeout(Q),Q=null),Z=t,J=W.apply(Y,K),Q||(Y=K=null)):Q||(Q=setTimeout(X,e)),J});ot(window,"message",xt),ot(window,"readystatechange",Mt),Mt()}function rt(){}function ot(t,e,n,r){"addEventListener"in window?t.addEventListener(e,n,!!H&&(r||{})):"attachEvent"in window&&t.attachEvent("on"+e,n)}function it(t,e,n){"removeEventListener"in window?t.removeEventListener(e,n,!1):"detachEvent"in window&&t.detachEvent("on"+e,n)}function at(t){return t.charAt(0).toUpperCase()+t.slice(1)}function st(t){return C+"["+I+"] "+t}function ut(t){S&&"object"===r(window.console)&&console.log(st(t))}function ct(t){"object"===r(window.console)&&console.warn(st(t))}function lt(){var t,r;!function(){function t(t){return"true"===t}var r=g.substr(P).split(":");I=r[0],a=e!==r[1]?Number(r[1]):a,l=e!==r[2]?t(r[2]):l,S=e!==r[3]?t(r[3]):S,w=e!==r[4]?Number(r[4]):w,n=e!==r[6]?t(r[6]):n,s=r[7],m=e!==r[8]?r[8]:m,i=r[9],c=r[10],x=e!==r[11]?Number(r[11]):x,b.enable=e!==r[12]&&t(r[12]),O=e!==r[13]?r[13]:O,z=e!==r[14]?r[14]:z}(),ut("Initialising iFrame ("+location.href+")"),function(){function t(t,e){return"function"==typeof t&&(ut("Setup custom "+e+"CalcMethod"),q[e]=t,t="custom"),t}var e;"iFrameResizer"in window&&Object===window.iFrameResizer.constructor&&(e=window.iFrameResizer,ut("Reading data from page: "+JSON.stringify(e)),L="messageCallback"in e?e.messageCallback:L,B="readyCallback"in e?e.readyCallback:B,T="targetOrigin"in e?e.targetOrigin:T,m="heightCalculationMethod"in e?e.heightCalculationMethod:m,z="widthCalculationMethod"in e?e.widthCalculationMethod:z,m=t(m,"height"),z=t(z,"width")),ut("TargetOrigin for parent set to: "+T)}(),e===s&&(s=a+"px"),dt("margin",(-1!==(r=s).indexOf("-")&&(ct("Negative CSS value ignored for margin"),r=""),r)),dt("background",i),dt("padding",c),(t=document.createElement("div")).style.clear="both",t.style.display="block",document.body.appendChild(t),yt(),mt(),document.documentElement.style.height="",document.body.style.height="",ut('HTML & body height set to "auto"'),ut("Enable public methods"),F.parentIFrame={autoResize:function(t){return!0===t&&!1===n?(n=!0,vt()):!1===t&&!0===n&&(n=!1,gt()),n},close:function(){Tt(0,0,"close"),ut("Disable outgoing messages"),A=!1,ut("Remove event listener: Message"),it(window,"message",xt),!0===n&>()},getId:function(){return I},getPageInfo:function(t){"function"==typeof t?(U=t,Tt(0,0,"pageInfo")):(U=function(){},Tt(0,0,"pageInfoStop"))},moveToAnchor:function(t){b.findTarget(t)},reset:function(){kt("parentIFrame.reset")},scrollTo:function(t,e){Tt(e,t,"scrollTo")},scrollToOffset:function(t,e){Tt(e,t,"scrollToOffset")},sendMessage:function(t,e){Tt(0,0,"message",JSON.stringify(t),e)},setHeightCalculationMethod:function(t){m=t,yt()},setWidthCalculationMethod:function(t){z=t,mt()},setTargetOrigin:function(t){ut("Set targetOrigin: "+t),T=t},size:function(t,e){Et("size","parentIFrame.size("+(t||"")+(e?","+e:"")+")",t,e)}},vt(),b=function(){function t(t){var n=t.getBoundingClientRect(),r={x:window.pageXOffset!==e?window.pageXOffset:document.documentElement.scrollLeft,y:window.pageYOffset!==e?window.pageYOffset:document.documentElement.scrollTop};return{x:parseInt(n.left,10)+parseInt(r.x,10),y:parseInt(n.top,10)+parseInt(r.y,10)}}function n(n){var r=n.split("#")[1]||n,o=decodeURIComponent(r),i=document.getElementById(o)||document.getElementsByName(o)[0];e!==i?function(e){var n=t(e);ut("Moving to in page link (#"+r+") at x: "+n.x+" y: "+n.y),Tt(n.y,n.x,"scrollToOffset")}(i):(ut("In page link (#"+r+") not found in iFrame, so sending to parent"),Tt(0,0,"inPageLink","#"+r))}function r(){""!==location.hash&&"#"!==location.hash&&n(location.href)}return b.enable?Array.prototype.forEach&&document.querySelectorAll?(ut("Setting up location.hash handlers"),Array.prototype.forEach.call(document.querySelectorAll('a[href^="#"]'),(function(t){"#"!==t.getAttribute("href")&&ot(t,"click",(function(t){t.preventDefault(),n(this.getAttribute("href"))}))})),ot(window,"hashchange",r),setTimeout(r,p)):ct("In page linking not fully supported in this browser! (See README.md for IE8 workaround)"):ut("In page linking not enabled"),{findTarget:n}}(),Et("init","Init message from host page"),B()}function dt(t,n){e!==n&&""!==n&&"null"!==n&&(document.body.style[t]=n,ut("Body "+t+' set to "'+n+'"'))}function pt(t){var e={add:function(e){function n(){Et(t.eventName,t.eventType)}V[e]=n,ot(window,e,n,{passive:!0})},remove:function(t){var e=V[t];delete V[t],it(window,t,e)}};t.eventNames&&Array.prototype.map?(t.eventName=t.eventNames[0],t.eventNames.map(e[t.method])):e[t.method](t.eventName),ut(at(t.method)+" event listener: "+t.eventType)}function ft(t){pt({method:t,eventType:"Animation Start",eventNames:["animationstart","webkitAnimationStart"]}),pt({method:t,eventType:"Animation Iteration",eventNames:["animationiteration","webkitAnimationIteration"]}),pt({method:t,eventType:"Animation End",eventNames:["animationend","webkitAnimationEnd"]}),pt({method:t,eventType:"Input",eventName:"input"}),pt({method:t,eventType:"Mouse Up",eventName:"mouseup"}),pt({method:t,eventType:"Mouse Down",eventName:"mousedown"}),pt({method:t,eventType:"Orientation Change",eventName:"orientationchange"}),pt({method:t,eventType:"Print",eventName:["afterprint","beforeprint"]}),pt({method:t,eventType:"Ready State Change",eventName:"readystatechange"}),pt({method:t,eventType:"Touch Start",eventName:"touchstart"}),pt({method:t,eventType:"Touch End",eventName:"touchend"}),pt({method:t,eventType:"Touch Cancel",eventName:"touchcancel"}),pt({method:t,eventType:"Transition Start",eventNames:["transitionstart","webkitTransitionStart","MSTransitionStart","oTransitionStart","otransitionstart"]}),pt({method:t,eventType:"Transition Iteration",eventNames:["transitioniteration","webkitTransitionIteration","MSTransitionIteration","oTransitionIteration","otransitioniteration"]}),pt({method:t,eventType:"Transition End",eventNames:["transitionend","webkitTransitionEnd","MSTransitionEnd","oTransitionEnd","otransitionend"]}),"child"===O&&pt({method:t,eventType:"IFrame Resized",eventName:"resize"})}function ht(t,e,n,r){return e!==t&&(t in n||(ct(t+" is not a valid option for "+r+"CalculationMethod."),t=e),ut(r+' calculation method set to "'+t+'"')),t}function yt(){m=ht(m,y,tt,"height")}function mt(){z=ht(z,j,et,"width")}function vt(){var t;!0===n?(ft("add"),t=0>w,window.MutationObserver||window.WebKitMutationObserver?t?bt():u=function(){function t(t){function e(t){!1===t.complete&&(ut("Attach listeners to "+t.src),t.addEventListener("load",o,!1),t.addEventListener("error",i,!1),s.push(t))}"attributes"===t.type&&"src"===t.attributeName?e(t.target):"childList"===t.type&&Array.prototype.forEach.call(t.target.querySelectorAll("img"),e)}function n(t){ut("Remove listeners from "+t.src),t.removeEventListener("load",o,!1),t.removeEventListener("error",i,!1),function(t){s.splice(s.indexOf(t),1)}(t)}function r(t,r,o){n(t.target),Et(r,o+": "+t.target.src,e,e)}function o(t){r(t,"imageLoad","Image loaded")}function i(t){r(t,"imageLoadFailed","Image load failed")}function a(e){Et("mutationObserver","mutationObserver: "+e[0].target+" "+e[0].type),e.forEach(t)}var s=[],u=window.MutationObserver||window.WebKitMutationObserver,c=function(){var t=document.querySelector("body");return c=new u(a),ut("Create body MutationObserver"),c.observe(t,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0}),c}();return{disconnect:function(){"disconnect"in c&&(ut("Disconnect body MutationObserver"),c.disconnect(),s.forEach(n))}}}():(ut("MutationObserver not supported in this browser!"),bt())):ut("Auto Resize disabled")}function gt(){ft("remove"),null!==u&&u.disconnect(),clearInterval(_)}function bt(){0!==w&&(ut("setInterval: "+w+"ms"),_=setInterval((function(){Et("interval","setInterval: "+w)}),Math.abs(w)))}function wt(t,e){var n=0;return e=e||document.body,n="defaultView"in document&&"getComputedStyle"in document.defaultView?null!==(n=document.defaultView.getComputedStyle(e,null))?n[t]:0:function(t){if(/^\d+(px)?$/i.test(t))return parseInt(t,o);var n=e.style.left,r=e.runtimeStyle.left;return e.runtimeStyle.left=e.currentStyle.left,e.style.left=t||0,t=e.style.pixelLeft,e.style.left=n,e.runtimeStyle.left=r,t}(e.currentStyle[t]),parseInt(n,o)}function _t(t,e){for(var n=e.length,r=0,o=0,i=at(t),a=$(),s=0;so&&(o=r);return a=$()-a,ut("Parsed "+n+" HTML elements"),ut("Element position calculated in "+a+"ms"),function(t){t>R/2&&ut("Event throttle increased to "+(R=2*t)+"ms")}(a),o}function St(t){return[t.bodyOffset(),t.bodyScroll(),t.documentElementOffset(),t.documentElementScroll()]}function Ct(t,e){var n=document.querySelectorAll("["+e+"]");return 0===n.length&&(ct("No tagged elements ("+e+") found on page"),document.querySelectorAll("body *")),_t(t,n)}function Pt(){return document.querySelectorAll("body *")}function It(t,n,r,o){var i,a;!function(){function t(t,e){return!(Math.abs(t-e)<=x)}return i=e!==r?r:tt[m](),a=e!==o?o:et[z](),t(h,i)||l&&t(D,a)}()&&"init"!==t?!(t in{init:1,interval:1,size:1})&&(m in E||l&&z in E)?kt(n):t in{interval:1}||ut("No change in size detected"):(Ot(),Tt(h=i,D=a,t))}function Et(t,e,n,r){M&&t in d?ut("Trigger event cancelled: "+t):(t in{reset:1,resetPage:1,init:1}||ut("Trigger event: "+e),"init"===t?It(t,e,n,r):nt(t,e,n,r))}function Ot(){M||(M=!0,ut("Trigger event lock on")),clearTimeout(N),N=setTimeout((function(){M=!1,ut("Trigger event lock off"),ut("--")}),p)}function At(t){h=tt[m](),D=et[z](),Tt(h,D,t)}function kt(t){var e=m;m=y,ut("Reset trigger event: "+t),Ot(),At("reset"),m=e}function Tt(t,n,r,o,i){var a;!0===A&&(e===i?i=T:ut("Message targetOrigin: "+i),ut("Sending message to host page ("+(a=I+":"+t+":"+n+":"+r+(e!==o?":"+o:""))+")"),k.postMessage(C+a,i))}function xt(e){var n,r={init:function(){g=e.data,k=e.source,lt(),f=!1,setTimeout((function(){v=!1}),p)},reset:function(){v?ut("Page reset ignored by init"):(ut("Page size reset by host page"),At("resetPage"))},resize:function(){Et("resizeParent","Parent window requested size check")},moveToAnchor:function(){b.findTarget(i())},inPageLink:function(){this.moveToAnchor()},pageInfo:function(){var t=i();ut("PageInfoFromParent called from parent: "+t),U(JSON.parse(t)),ut(" --")},message:function(){var t=i();ut("MessageCallback called from parent: "+t),L(JSON.parse(t)),ut(" --")}};function o(){return e.data.split("]")[1].split(":")[0]}function i(){return e.data.substr(e.data.indexOf(":")+1)}function a(){return e.data.split(":")[2]in{true:1,false:1}}C===(""+e.data).substr(0,P)&&(!1===f?(n=o())in r?r[n]():!t.exports&&"iFrameResize"in window||"jQuery"in window&&"iFrameResize"in window.jQuery.prototype||a()||ct("Unexpected message ("+e.data+")"):a()?r.init():ut('Ignored message of type "'+o()+'". Received before initialization.'))}function Mt(){"loading"!==document.readyState&&window.parent.postMessage("[iFrameResizerChild]Ready","*")}}()},27403:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(91621),n(27481),n(90105),n(14266),n(47818),n(14718),n(57188),n(44396),n(25226),n(13521),n(17186),n(25766),n(11062),n(44594),n(92947),function(e){"use strict";if("undefined"!=typeof window){var n,o=0,i=!1,a=!1,s=7,u="[iFrameSizer]",c=u.length,l=null,d=window.requestAnimationFrame,p={max:1,scroll:1,bodyScroll:1,documentElementScroll:1},f={},h=null,y={autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",closedCallback:function(){},initCallback:function(){},messageCallback:function(){C("MessageCallback function not defined")},resizedCallback:function(){},scrollCallback:function(){return!0}},m={};window.jQuery&&((n=window.jQuery).fn?n.fn.iFrameResize||(n.fn.iFrameResize=function(t){return this.filter("iframe").each((function(e,n){z(n,t)})).end()}):S("","Unable to bind to jQuery, it is not fully loaded.")),"function"==typeof define&&define.amd?define([],q):"object"===r(t)&&"object"===r(t.exports)&&(t.exports=q()),window.iFrameResize=window.iFrameResize||q()}function v(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function g(t,e,n){"addEventListener"in window?t.addEventListener(e,n,!1):"attachEvent"in window&&t.attachEvent("on"+e,n)}function b(t,e,n){"removeEventListener"in window?t.removeEventListener(e,n,!1):"detachEvent"in window&&t.detachEvent("on"+e,n)}function w(t){return f[t]?f[t].log:i}function _(t,e){P("log",t,e,w(t))}function S(t,e){P("info",t,e,w(t))}function C(t,e){P("warn",t,e,!0)}function P(t,e,n,o){!0===o&&"object"===r(window.console)&&console[t](function(t){return u+"["+function(t){var e="Host page: "+t;return window.top!==window.self&&(e=window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+t:"Nested host page: "+t),e}(t)+"]"}(e),n)}function I(t){function e(){n("Height"),n("Width"),R((function(){N(P),T(I),p("resizedCallback",P)}),P,"init")}function n(t){var e=Number(f[I]["max"+t]),n=Number(f[I]["min"+t]),r=t.toLowerCase(),o=Number(P[r]);_(I,"Checking "+r+" is in range "+n+"-"+e),oe&&(o=e,_(I,"Set "+r+" to max value")),P[r]=""+o}function r(t){return w.substr(w.indexOf(":")+s+t)}function o(t,e){var n,r;n=function(){var n,r;D("Send Page Info","pageInfo:"+(n=document.body.getBoundingClientRect(),r=P.iframe.getBoundingClientRect(),JSON.stringify({iframeHeight:r.height,iframeWidth:r.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(r.top-n.top,10),offsetLeft:parseInt(r.left-n.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset})),t,e)},m[r=e]||(m[r]=setTimeout((function(){m[r]=null,n()}),32))}function i(t){var e=t.getBoundingClientRect();return k(I),{x:Math.floor(Number(e.left)+Number(l.x)),y:Math.floor(Number(e.top)+Number(l.y))}}function a(t){var e=t?i(P.iframe):{x:0,y:0},n={x:Number(P.width)+e.x,y:Number(P.height)+e.y};_(I,"Reposition requested from iFrame (offset x:"+e.x+" y:"+e.y+")"),window.top!==window.self?window.parentIFrame?window.parentIFrame["scrollTo"+(t?"Offset":"")](n.x,n.y):C(I,"Unable to scroll to requested position, window.parentIFrame not found"):(l=n,d(),_(I,"--"))}function d(){!1!==p("scrollCallback",l)?T(I):x()}function p(t,e){return E(I,t,e)}var h,y,v,w=t.data,P={},I=null;"[iFrameResizerChild]Ready"===w?function(){for(var t in f)D("iFrame requested init",j(t),document.getElementById(t),t)}():u===(""+w).substr(0,c)&&w.substr(c).split(":")[0]in f?(v=w.substr(c).split(":"),P={iframe:f[v[0]]&&f[v[0]].iframe,id:v[0],height:v[1],width:v[2],type:v[3]},I=P.id,f[I]&&(f[I].loaded=!0),(y=P.type in{true:1,false:1,undefined:1})&&_(I,"Ignoring init message from meta parent page"),!y&&function(t){var e=!0;return f[t]||(e=!1,C(P.type+" No settings for "+t+". Message was: "+w)),e}(I)&&(_(I,"Received: "+w),h=!0,null===P.iframe&&(C(I,"IFrame ("+P.id+") not found"),h=!1),h&&function(){var e,n=t.origin,r=f[I]&&f[I].checkOrigin;if(r&&""+n!="null"&&!(r.constructor===Array?function(){var t=0,e=!1;for(_(I,"Checking connection is from allowed list of origins: "+r);tf[u]["max"+t])throw new Error("Value for min"+t+" can not be greater than max"+t)}n("Height"),n("Width"),e("maxHeight"),e("minHeight"),e("maxWidth"),e("minWidth")}(),"number"!=typeof(f[u]&&f[u].bodyMargin)&&"0"!==(f[u]&&f[u].bodyMargin)||(f[u].bodyMarginV1=f[u].bodyMargin,f[u].bodyMargin=f[u].bodyMargin+"px"),a=j(u),(s=v())&&function(e){t.parentNode&&new e((function(e){e.forEach((function(e){Array.prototype.slice.call(e.removedNodes).forEach((function(e){e===t&&A(t)}))}))})).observe(t.parentNode,{childList:!0})}(s),g(t,"load",(function(){var n,r;D("iFrame.onload",a,t,e,!0),n=f[u]&&f[u].firstRun,r=f[u]&&f[u].heightCalculationMethod in p,!n&&r&&M({iframe:t,height:0,width:0,type:"init"})})),D("init",a,t,e,!0),Function.prototype.bind&&f[u]&&(f[u].iframe.iFrameResizer={close:A.bind(null,f[u].iframe),removeListeners:O.bind(null,f[u].iframe),resize:D.bind(null,"Window resize","resize",f[u].iframe),moveToAnchor:function(t){D("Move to anchor","moveToAnchor:"+t,f[u].iframe,u)},sendMessage:function(t){D("Send Message","message:"+(t=JSON.stringify(t)),f[u].iframe,u)}}))}function F(t,e){null===h&&(h=setTimeout((function(){h=null,t()}),e))}function L(t){_("window","Trigger event: "+t),F((function(){U("Window "+t,"resize")}),16)}function B(){"hidden"!==document.visibilityState&&(_("document","Trigger event: Visiblity change"),F((function(){U("Tab Visable","resize")}),16))}function U(t,e){function n(t){return f[t]&&"parent"===f[t].resizeFrom&&f[t].autoResize&&!f[t].firstRun}for(var r in f)n(r)&&D(t,e,document.getElementById(r),r)}function q(){function t(t,e){e&&(function(){if(!e.tagName)throw new TypeError("Object is not a valid DOM element");if("IFRAME"!==e.tagName.toUpperCase())throw new TypeError("Expected